2

I have this inputs with non-numeric indexes with jQuery:

<input name="attributes['index1']" class="text_inputs" />
<input name="attributes['index2']" class="text_inputs" />
<input name="attributes['index3']" class="text_inputs" />

and this jquery code:

var attrs = new Array();
$.map( $('input.text_inputs'), function(obj, idx) {
    attrs['here_the_index_from_input'] = obj.value;
});

So I want to add each index from inputs to attrs array index. Thanks in advance!

1
  • Does 'here_the_index_from_input' mean, for example, 'index1', 'index2', and 'index3'? Commented Jun 9, 2011 at 14:44

3 Answers 3

3

You're mixing up a bunch of different concepts.

  • You specifically said "non-numeric indices," which means you shouldn't use an array at all.
  • If you're not going to use the array returned by map, use each instead.
  • If you have a jQuery collection already, there's no need to use the $.func form. Just use .func.

    var attrs = {};
    $('input.text_inputs').each(function()
    {
        var $this = $(this),
            name = $this.prop('name'),
            val = $this.val();
    
        name = name.replace(/^attributes\['|'\]$/g, '');
    
        attrs[name] = val;
    });
    

I assumed that by 'here_the_index_from_input' you mean, for example, 'index1', 'index2', and 'index3'.

Demo: http://jsfiddle.net/mattball/t2hX5/

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

Comments

0
  var attrs = [];
  $.each($('input.text_inputs'), function(){
      attrs[$(this).attr('nameOfIndexAttribute')] = $(this).val();
  });

Comments

0

You can do it this way (if i unerstood correctly what you want)

var attrs = {};
$.map( $('input.text_inputs'), function(obj, idx) {
    attrs[obj.name] = obj.value;
});

attrs is an associative array with the names of the input field as the key and the values of the input field as values.

EDIT - use an object as correctly stated in the comment, not an array

2 Comments

var attrs = {}; or var attrs = new Object(); Not var attrs = new Array();. Arrays are for numerical indices only. Just because you can tack on ad-hoc properties doesn't mean you should.
You are right. I'll edit the answer and keep that in mind!What i wanted to show was how to use obj.name to get the name of the input.

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.