Question

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?

Was it helpful?

Solution

Try This:

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

Working Demo

OTHER TIPS

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][]');

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/

use this code:

var counter = 1;
  $('a.mylink').click(function(){
  $(':text').attr('value', 'myInput[1][sausages][' + counter++ + '][]');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top