Make javaScript/jQuery array of multiple input field values
Simple question i can't f开发者_运维知识库igure out. I'd like to make a JavaScript array of input values but can't figure out the simple code.
Here's the HTML:
<input class="email" value="joe@smith.com"></input>
<input class="email" value="bob@jones.com"></input>
Here's the not yet correct JS/jQuery which attempts to make an array:
$.fn.valuesArr = function()
{
var a = [];
$.each(this, function(i, field){
a.push(field.value);
});
return a;
}
var emailArr=$('.email').valuesArr();
Ultimately, this is what i'd like the emailArr to be:
emailArr= ["joe@smith.com", "bob@jones.com"];
Not sure what is wrong with my valuesArr function, any JS and/or jQuery-based solution would be greatly appreciated!
This should get all the elements of class email it value and then assign it to the email array.
$("action").click(function () {
var emails=new Array();
var j=0;
$(".email").each(function(){
emails[j]=$(this).val();
j++;
});
});
The original script was correct as Pat said. The problem was with how the script was called. The original script will work if you do either of the following:
- making sure the original script is below the tags in your your HTML file
- encapsulating the script in a jQuery document.ready function, i.e., $(function(){ --$.each function() -- });
Thanks to both Pat and COLD TOLD for their help,
精彩评论