admin管理员组

文章数量:1332395

I have the following code;

$('#btnSave').click(function (e) {
    $("input:text").each(function (index, value) {
        var el = $(this);
        if (el.val().length == 0) { el.css('border', '1px solid red') }
        return false;
    });
});

Here, all the input text elements are dynamically created hence I can never validate whether they are empty or not..

How do I go and use .on() with .each() ? I googled with no luck.. Thanks in advance..

I have the following code;

$('#btnSave').click(function (e) {
    $("input:text").each(function (index, value) {
        var el = $(this);
        if (el.val().length == 0) { el.css('border', '1px solid red') }
        return false;
    });
});

Here, all the input text elements are dynamically created hence I can never validate whether they are empty or not..

How do I go and use .on() with .each() ? I googled with no luck.. Thanks in advance..

Share Improve this question asked Sep 7, 2012 at 17:24 Subliminal HashSubliminal Hash 13.7k21 gold badges77 silver badges108 bronze badges 4
  • That code should work as long as the elements are created before the button is clicked. .on() is used for attaching events. – James Kleeh Commented Sep 7, 2012 at 17:26
  • This looks like it will work fine, what problem are you having? – BZink Commented Sep 7, 2012 at 17:27
  • 2 Why do you return false every time each calls your function? – Rikki Commented Sep 7, 2012 at 17:31
  • Thank you for your help.. btnSave was an asp button which was causing postback. When I turned it into a standard button, it somehow worked.. I don't know why but I'll check... – Subliminal Hash Commented Sep 7, 2012 at 17:33
Add a ment  | 

2 Answers 2

Reset to default 4

Your code is pretty much fine, but get rid of the return false;. It stops the .each() loop after the first input is hit.

jsFiddle example

It should not be a problem until and unless the elements are not on the page when you click on the page.. Also because you are returning return false ; when the field is empty only the first textbox will be given the border.. Others will be left out even when empty..

Try this

​$(function() {
    $('#btn1').on('click' , function() {
        var inp = '';
        for(var i=1;i< 6;i++){
           inp += '<input type="text" id="txt' + i + '"/>'
        }   
        $('.textboxes').append(inp);

       var isError = false;
       $("input:text").each(function (index, value) {
            var el = $(this);
            if (el.val() == '') { 
               el.addClass('error');
               isError = true;
            }
        });

            if(isError){return false;}    
    });    

});​

Also check this working example... FIDDLE

本文标签: javascriptRunning jQueryeach() on dynamically created elementsStack Overflow