Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through array of dynamically-added elements

Tags:

jquery

New to jQuery, requesting assistance with something I'm having trouble figuring out.

A cloned table row contains an <input type="text" name="dt[]" id="dt1"> field. Below is the template row that gets cloned.

<table id="MyTable" name="MyTable">
    <tr name="tr3" id="tr3">
        <td>
            <input type="text" name="dt[]" id="dt1">
        </td>
        <td>
            <input type="file" name="fff[]" id="ff1">
        </td>
    </tr>
</table>

The user could potentially create several of these fields and I am trying to figure out how to loop through them all and verify there is text in them before submitting the form.

Note that I must use the jQuery .on() method to access the form elements. How would the loop need to be coded? Initially, I've been trying this (EDITED):

$(document).on('click','#sub1',function() {
    var d1 = $("[name^=dt]").val();
    alert(d1);
    if (d1 !=""){
        $("#TheForm").submit();
    } else {
        alert("Empty fields!");
    }
});

And this:

var d1 = $("#dt1").val();
alert(d1);

And this:

var d1 = $("#^dt").val();
alert(d1);

but haven't been able to get at the data.


EDIT: As requested, this code clones the row:

$(document).on('click', '#add_row', function() {
    $("table#MyTable tr:nth-child(4)")
        .clone()
        .show()
        .find("input, span").each(function() {
            $(this)
                .val('')
                .attr('id', function(_, id) {
                    var newcnt = id + count;
                    return id + count;
                    });
        })
        .end()
        .appendTo("table")
        ;

    count++;
    if (count == 2) {
        $('#add_row').prop('disabled', 'disabled');
    }
}); //end add_row Function
like image 208
cssyphus Avatar asked Sep 14 '12 19:09

cssyphus


1 Answers

Your HTML is not in correct format. you should do:

<input type="text" name="dt[]">

and then loop over like:

$('input[name^=dt]').each(function() {
  // code
  alert( this.value ); // $(this).val()
});

What you're trying to do can not be possible with id attribute, but possible with name attribute. id should always be unique.


Beside that

You can use a common class name to all inputs and then loop over then like:

$('input.common_cls').each(function() {
  // code
});

Note

"#^dt" is not a valid selector at all. Correct syntax would be

'input[name^=dt]'

OR

input[id^=dt].


You may implement the validation like below

// this function will return true if no empty
// input exists, otherwise it will return false

function noEmptyExists() {
    return $('input[name^=dt]').filter(function() {
        return !$.trim( this.value );
    }).length === 0;
}

$(document).on('click','#sub1',function() {
   if( noEmptyExists() ) {
      alert('Success');
   } else {
      alert('Failed');
   }
});

Working sample


According to PROGRESS UPDATE

this.val() is wrong.

Change this line to:

$(this).val()

After a discussion in Chat and after solving the clone issue

Full code

$(document).ready(function() {
    var count = 1;
    alert('doc ready');
    var row = $("table#MyTable tr:eq(1)");
    $(document).on('click', '#sub1', function() {
        if (noEmptyExists()) {
            alert('Success');
        } else {
            alert('Failed');
        }
    });

    $(document).on('click', '#add_row', function() {
        row.clone(true).find("input").each(function() {
            $(this).val('').attr('id', function(_, id) {
                var newcnt = id + count;
                return id + count;
            });
        }).end().appendTo("table");
    });

});

function noEmptyExists() {
    return $('input[name^=dt]').filter(function() {
        return !$.trim(this.value);
    }).length === 0;
}

Working sample

like image 190
thecodeparadox Avatar answered Nov 02 '22 23:11

thecodeparadox