I am looking for some urgent help with jquery , i have some input boxes and i want so retrieve their value as an array, the problem is that all the input boxes will be created dynamically with an add more button, so i am not sure how many of they would be, my code to create dynamic boxes is here.
$(function(){
x = 0;
$('#addmore a').live("click",function(){
x++;
$('#addmore').append('<input type="text" id="fname_' + x + '"/></p>');
return false;
});
});
now let say a person clicked addmore for 3 times now i will have 3 inputboxes with #fname_1, #fname_2 and #fname_3. now i want all the 3 values inside an array.
Thanks
-
add a class name to the input elements and query thatEsailija– Esailija2011年10月16日 14:54:22 +00:00Commented Oct 16, 2011 at 14:54
-
How is PHP related to that problem?Felix Kling– Felix Kling2011年10月16日 14:54:23 +00:00Commented Oct 16, 2011 at 14:54
-
Please try to keep confusion to a minimum ...TigOldBitties– TigOldBitties2011年10月16日 14:56:59 +00:00Commented Oct 16, 2011 at 14:56
-
@felix ... sorry dude that was a mistake and question is now editedAman Virk– Aman Virk2011年10月16日 14:57:03 +00:00Commented Oct 16, 2011 at 14:57
-
@ esailija :- can you be more descriptiveAman Virk– Aman Virk2011年10月16日 14:59:08 +00:00Commented Oct 16, 2011 at 14:59
3 Answers 3
Add name attribute like this:
$(function(){
x = 0;
$('#addmore a').live("click",function(){
x++;
$('#addmore').append('<input type="text" name="fname[]" id="fname_' + x + '"/></p>');
return false;
});
});
When you submit, you will have $_POST['fname'], which hold array of your auto-generated input boxes.
By the way, are you sure that you need to put </p> after each input?!
You can do it without adding anything (name or class) with such code:
var values = $.map($("#addmore input[id^='fname_']"), function(element, index) {
return element.value;
});
This will iterate over all inputs with id starting with "fname_" and map their value into single array.
1 Comment
$( 'input[id^="fname_"]', '#addmore' ). (Doing a page-level query for INPUT elements is not efficient.)If this has nothing to do with php:
$(function(){
x = 0;
$('#addmore a').live("click",function(){
x++; //Add "text-field" class
$('#addmore').append('<input type="text" class="text-field" id="fname_' + x + '"/></p>');
return false;
});
});
function getFieldValues(){
var r = [];
//Query text field class and push the values into an array
jQuery( ".text-field").each(
function(){
r.push( this.value );
}
);
return r; //returns an array with the values
}
3 Comments
$ name safely: jQuery( function ( $ ) { ... });. Read here under section "Aliasing the jQuery Namespace".