Search code examples
jquerydata-bindingreal-time

Reusable real time display with jQuery


I'm attempting to update some text fields based on the the data that is entered into an input field in real time using jQuery. I have gotten a rough example of this working, but it's not very reusable at it requires a function be created for each input. I was hoping that there might be a more dynamic/efficient way to perform the same task?

$('#name').keyup(function () {
        $('#label-name').text($(this).val());
    });

    $('#address').keyup(function () {
        $('#label-address').text($(this).val());
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" type="text" placeholder="Name">
    <input id="address" type="text" placeholder="Address">
    <input id="city" type="text" placeholder="City">
    <select name="state" id="state">
        <option value="none">--</option>
        <option value="state1">State 1</option>
        <option value="state2">State 2</option>
    </select>
    <input id="zip" type="text" placeholder="Zip">
    <input id="additional" type="text" placeholder="Additional info">
    
    <p id="label-name"></p>
    <p id="label-address"></p>
    <p id="label-city"></p>
    <p id="label-state"></p>
    <p id="label-zip"></p>
    <p id="label-additional"></p>


Solution

  • If you can guarantee that the ids will always be related as you've shown, you could add a class to your inputs and do something like this:

    $('.input').keyup(function () {
        $('#label-' + this.id).text(this.value);
    });