Search code examples
javascriptjqueryhtmlkeyup

jQuery detecting changes on two elements using keyup()


HTML:

<form>
    <input type="text" id="target" placeholder="example.com">
    <input type="checkbox" name="http" id="http" value="http"> http://
</form>

<div id="possible-targets">
    <h4>Possible matches: </h4>
</div>

JS:

var target_value;

$(window).load(function () {

    $('#target').keyup(function () {
        target_value = $('#target').val();

        if (target_value == '') {
            $('#target-match').remove();
        } else if ($('#target-match').length == 0) {
            $('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
        } else if ($('#target-match').length != 0) {
            $('#target-match').html(target_value);
        }

        if ($('#http').prop('checked')) {
            if ($('#target-match-h').length == 0) {
                $('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
            } else {
                $('#target-match-h').html('http://' + target_value);
            }
        } else {
            $('#target-match-h').remove();
        }
    });
});

Here is a JSFiddle: http://jsfiddle.net/h2Uw4/

Now when I start typing in the text input field I can see a live change in the possible-targets div, but when I click on the http:// checkbox it still needs to type at least one more character in the text input field to make a live change and add another possible target.

I tried to use keyup() on both #target (the text input) and #http (the checkbox) but it didn't work:

$('#target, #http').keyup()


Solution

  • Create a function and pass it to event handlers.

    Example Code

    var yourFunc = function () {
           //Your code
    };
    $('#target').keyup(yourFunc);
    $('#http').change(yourFunc); 
    

    DEMO

    As per @DavidThomas comments you can also use

    $('#target, #http').on('change keyup', yourFunc)
    

    DEMO 2