How to get the class of an input inside a jQuery each loop?
I have function which appends inpu开发者_Python百科ts inside a list item when a link is clicked. I then loop through these inputs using an each loop using the code below. It is working correctly as shown, however instead of using field.name I want to use the class of the input as the array key but when i try to do this the class is shown as undefined.
Here is the code I am currently using:
var values = {};
$.each($('li :input').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
Here is the code I have inside the list item once I have appended the hidden inputs using jQuery append:
<li><input type="hidden" name="group" class="group" value="2"/><input type="hidden" name="condition" class="condition" value="isany"/><input type="hidden" name="value" class="value" value="1,2"/></li>
I can get the name attribute fine but class is always undefined.
Could anybody help with this?
try:
var values = {};
$('li :input').each(function() {
values[$(this).attr('name')] = $(this).val();
});
This work when I tested.
var values = {};
$('li input').each(function() {
values[$(this).attr('class')] = $(this).val();
});
alert(JSON.stringify(values));
I can't figure out how to get it to work with $.serializeArray, but this works. (change console.log
to $("body").append
if you don't have a console).
$.each($('input'),function(){console.log(this.className)})
Note that you use the native javascript this
rather than the jquery object $(this)
var values = {};
$.each($('li :input').serializeArray(), function(i, field) {
values[$(field).attr('class')] = field.value;
});
精彩评论