Reputation: 1537
Let's say i have this form:
<form method="post" name="b" >
<table>
<tr>
<td>Field A</td>
<td><input type='text' name='field[0][a]' id='field[0][a]'></td>
<td>Field B</td>
<td><textarea name='field[0][b]' id='field[0][b]'></textarea></td>
<td><button>remove</button></td>
</tr>
</table>
</div>
<div id="container"></div>
<button id="mybutton">add form</button>
<div align="center">
<p><button onClick="dadosFormulario()" value="Registar" name="registar">Registo</button></p>
</div>
</form>
and i have a jquery function that duplicates the inputs i have when i click the "add form" button. So, regarding that, i'm trying to save the values of the inputs with the .val() method of jquery.
So, if i have an input like this one:
<input type='text' name='teste' id='teste'>
i know that with this:
var v = $('#teste').val();
i can receive her value. However, if i have an array of inputs, and that's my situation since i can duplicate the fields of the form, how can i obtain the multiple values from the following inputs?
<input type='text' name='field[0][a]' id='field[0][a]'>
<input type='text' name='field[0][b]' id='field[0][b]'>
var v = $('#field[iterator][a]').val(); won't work, it results in 'undefined'.
jquery function where i can't get the values from the inputs with the val(); gives undefined:
$countForms = 1;
(function($){
$.fn.addForms = function(idform){
var myform = "<table>"+
" <tr>"+
" <td>Field A ("+$countForms+"):</td>"+
" <td><input type='text' name='field\\["+$countForms+"\\]\\[a\\]'></td>"+
" <td>Field B ("+$countForms+"):</td>"+
" <td><textarea name='field["+$countForms+"]['b']'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
if(idform=='mybutton'){
myform = $(myform);
$("button", $(myform)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform);
$countForms++;
}
};
})(jQuery);
$(function(){
$("#mybutton").bind("click", function(e){
e.preventDefault();
var idform=this.id;
if($countForms<3){
$("#container").addForms(idform);
}
});
});
Upvotes: 1
Views: 218
Reputation: 365
Add a class to inputs and do this
jQuery(document).ready(function($){
$('.inputs').each(function(index, object){
console.log($(object).val());
});
});
On your code you need change here:
var v = $('#field[iterator][a]').val();
to:
var v = $('#field\\['+iterator+'\\]\\[a\\]').val();
Upvotes: 1
Reputation: 51800
The character "[" is not neutral in jquery selectors :
$('#field[0][a]')
means : " select the items which have id "field", and also have an attribute named '0', and another attribute named 'a' "
You can :
id="field_0_a"
, and thus have $('#field_0_a')
work correctly,$('[name="field[0][a]"]')
Upvotes: 1
Reputation: 26320
The problem is that you have to escape special characters like the following:
$('[id="field[' + iterator + '][b]"]').val();
or
$('#field\\[' + iterator + '\\]\\[b\\]').val();
demo
Upvotes: 0