0

I couldn't find anything, but I feel like it's been asked before.

I have multiple inputs:

<input id="id1" class="abc" name="tags" "value="test1" />
<input id="id2" class="abc" name="tags" "value="test2" />

When the user changes the value of the input, I want the script to pick it up and assign it into an array.

What I have:

jQuery('.abc').change(function() {
        var id = jQuery(this).attr('id');
        var name = jQuery(this).attr('name');
        var value = jQuery(this).val();
        var ch = {};
        ch[id][name] = value;
        alert(ch[id][name]);
    });

But from the start, it didn't work. jQuery(this).attr('id') doesn't exist as a function. I think the reason this isn't working is because there isn't a specific class I am calling, but I don't know. Maybe I've been staring at code too much, but it's not working!

the error: can't convert undefined to object

3
  • Can you post the exact error message you receive? Also, where is ch defined? Commented Jan 29, 2013 at 21:41
  • where and how is ch defined? Commented Jan 29, 2013 at 21:41
  • edited: left out the array declaration, my bad! Commented Jan 29, 2013 at 21:52

2 Answers 2

2

You need to create a new object for ch[id]

jQuery('.abc').change(function () {
  var id = jQuery(this).attr('id');
  var name = jQuery(this).attr('name');
  var value = jQuery(this).val();
  var ch = {};
  ch[id] = {}; // <-- here
  ch[id][name] = value;
  alert(ch[id][name]);
});

http://jsfiddle.net/tq2CJ/

Sign up to request clarification or add additional context in comments.

Comments

0

In your case 'this' points to function() not to your instance of jQuery('.abc') as you might expect. See http://www.quirksmode.org/js/this.html for an explanation on this.

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.