简体   繁体   中英

jquery class selector only registering events on first element of class

im currently working on a form field highlighter in jquery and so far it works except it only works on the first line of the form and the rest of the fields do not register my focus events so that i may apply focus formatting i am currently using the following jquery code

    var debug = false;




    $(function(){

        $(".email-form tbody:last").AddFormLineToTable();

        $("#do-add-row").click(function () {

            if(debug)
            {
                alert("serialize click eventhandler fired");
            }

            $(".email-form tbody:last").AddFormLineToTable();
        });



        $(".does-focus-highlight").focusin(function(e){

            $(e.target).addClass("focus-highlight");
            if(debug){alert('field did focus');}
        });
        $(".does-focus-highlight").focusout(function(e){
            $(e.target).removeClass("focus-highlight");
            if(debug){alert('field did blur');}

        });


        $("#do-serialize").click(function(){
          if(debug)
          {
              alert("serialize click eventhandler fired");
          }
           var jsn = $("#contact-form").serializeArray();
        $("#serialize-target").val(JSON.stringify(jsn,null,2));



        });



    });

is there something im missing to catch these additional events the form fields that are not firing are being generated dunamically as well if that makes a difference as well which are being generated as follows

    var lineCount = 0;

jQuery.fn.AddFormLineToTable = function() {
    var o = $(this[0]);
    o.append('<tr id="contact-'+lineCount+'">' +
        '<td>Name: <input class="does-focus-highlight" id="contact-name-'+lineCount+'" name="contact-name-'+lineCount+'" type="text" required="required" /></td>' +
        '<td>Email: <input class="does-focus-highlight" id="contact-email-'+lineCount+'" name="contact-email-'+lineCount+'" type="email" required="required" /></td>' +
        '</tr>');

    lineCount++;
};

.click() binds events only to elements that are existing at the time of calling .click() . If you want the events to be handled for elements that are created later on, use .on() or .live() , depending on the version of jQuery you are using. Read the very helpful info here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM