2

I have function which appends inputs 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?

1
  • how're you trying to get the classname? Commented Mar 9, 2011 at 23:44

3 Answers 3

5

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));
Sign up to request clarification or add additional context in comments.

3 Comments

values[$(this).attr('class')] = $(this).val();
Hi, I tried this code and it works for the name attribute but when i try for class attribute which is what I want then it still returns class as undefined
Hi, here is what i have appended inside the list item: <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 but not the class
1

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)

Comments

0
var values = {};
$.each($('li :input').serializeArray(), function(i, field) {
    values[$(field).attr('class')] = field.value;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.