Search code examples
javascriptjquerydhtml

jquery iterating over elements and binding an event onto each element


I need to bind a keypress event to a form of elements that is built up dynamically, see below

<div class="Customer">
<select name="dropdown1" id="dropdown1">
</select>
<input type="textbox" name="firstname1" id="firstname1">
<input type="textbox" name="lastname1" id="lastname1">
</div>

<div class="Customer">
<select name="dropdown2" id="dropdown2">
</select>
<input type="textbox" name="firstname2" id="firstname2">
<input type="textbox" name="lastname2" id="lastname2">
</div>

... and repeat..

I need to check that whenever any of the elements above are changed that no other of the elements are empty.

The form also has several other elements in it although I only care about these highlighted in the code segment.

Many thanks,

I've tried the following code

$('.Customer').each(function (index) {

    alert("test");  // alerts the correct number of customer rows

    $("input:textbox").click(function() {
        alert("");
    })

});

solution should work with jQuery 1.3.2


Solution

  • See it working here

    <input type="checkbox" id="test" name="test" disabled="disabled">
    
    <div class="Customer">
    <select name="dropdown1" id="dropdown1">
        <option value="1.1">1.1</option>
        <option value="1.2">1.2</option>
    </select>
    <input type="text" name="firstname1" id="firstname1">
    <input type="text" name="lastname1" id="lastname1">
    </div>
    
    <div class="Customer">
    <select name="dropdown2" id="dropdown2">
        <option value="2.1">2.1</option>
        <option value="2.2">2.2</option>
    </select>
    <input type="text" name="firstname2" id="firstname2">
    <input type="text" name="lastname2" id="lastname2">
    </div>​
    
    $('.Customer input, .Customer select').bind("change keyup", function(){
         var me = $(this);
         var clicked = me.attr("name");
         var empty = false;
         $('.Customer input,select').each(function(){
             var elem = $(this);
                 if (elem.val() == "") {
                     empty = true;
                 }
         });
         if (empty) {
            $('#test').attr('disabled','disabled')
         } else {
            $('#test').removeAttr('disabled')
         }
    });​
    

    PS: there's no type textbos in input. It's text. In order to get a callback fired when something changed you use the "change" and not the "click" event. If you want it to work on both the inputs ans the dropdowns, you need "input, select"