3

I have an input field which looks something like this...

<input type='hidden' name='myInput[1][sausages][0][]' value='123' />

I need to change the value in the third set of square brackets when a user clicks on a button...

so something like

$("a.mylink").click( function() {
    $(this).siblings('input[name*=myInput]')..... CHANGE THE 0 to 1 in the third set of square brackets...
});

Any ideas how I can do this?

4 Answers 4

1

Try This:

$('input').attr('name',$('input').attr('name').replace(/\[\d+](?!.*\[\d)/, '[1]'))

Working Demo

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

Comments

1

You can use regex to replace the value like so:

var name = $('input [name*=myInput]').attr('name');
name.replace(/]$/, 'new value]');
$('input [name*=myInput]').attr('name', name);

The new value can be any number This regex replaces the last bracket with a new value: newvalue ]

Or if you want to change the 2nd to last bracket you can use this regex:

name.replace(/]\[\]$/, 'new value][]');

Comments

1

Try this

    var name = $('input[name*=myInput]').attr('name');
    var indexOfThirdBracket = name.indexOf('[', name.indexOf('sausages')) + 1;
    name = name.substring(0, indexOfThirdBracket) + '1' + name.substring(indexOfThirdBracket + 1);
    $('input[name*=myInput]').attr('name', name);

http://jsfiddle.net/3A592/

UPDATE

Solution without hard code value 'sausages'

var name = $('input[name*=myInput]').attr('name');
var parts = name.split('[');
parts[3] = parts[3].replace('0', '1');
name = parts.join('[');
$('input[name*=myInput]').attr('name', name);

http://jsfiddle.net/56rtG/

1 Comment

Using regexp much more better It doesn't depend on hard code value like in this sample.
0

use this code:

var counter = 1;
  $('a.mylink').click(function(){
  $(':text').attr('value', 'myInput[1][sausages][' + counter++ + '][]');
});

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.