0

I have the following input field, and I'm trying to figure out how to increment the value of a specific bracketed value...

How would I go about incrementing a particular bracketed value (i.e., title[0][subtitle][3] becomes title[0][subtitle][4])?

I've managed to partially get it working by hardcoding a value... The code below essentially does what I want, except that I can't figure out how to store and increment that particular value dynamically...

(also posted on jsfiddle: http://jsfiddle.net/492bD/ )...

<input type="text" class="form-text" value="" name="title[0][subtitle][0]">
<button id="clickme">Click me</button>
​
$('#clickme').live('click', function() { 
var lastSubTitle = $('input.form-text').attr('name');
var newSubTitle = lastSubTitle.replace(/^(.*\[[0-9]+\].*)(\[[0-9]+\])(.*)$/, '$1[20]$3');
alert(newSubTitle);
});
1
  • which value do you want to store? Commented Sep 23, 2012 at 19:06

2 Answers 2

1

Is there some reason you don't want to just use two (or more) properties and increment them separately?

<input type="text" class="form-text" value="" data-title="0" data-subtitle="0">
<button id="clickme">Click me</button>
​
$('#clickme').live('click', function() {
    var formText$ = $('input.form-text');
    formText$.attr('data-subtitle', +formText$.attr('data-subtitle') + 1); 
    alert(formText$.attr('data-subtitle'));
});​

If you need the name to have the value in that particular format, you can then just set the name property after incrementing the data.

formText$.attr('name', 'title[' + formText$.attr('data-title') +
                       '][subtitle][' + formText$.attr('data-subtitle') + ']');

You can see it at http://jsfiddle.net/tMcxH/1/.

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

Comments

0

You can do it without referring to complex regex, this is a solution done with string functions:

lastSubTitle = "title[0][subtitle][0]";
var n = lastSubTitle.substr(0, lastSubTitle.length -1);
var f = n.substr(n.lastIndexOf('[')+1);
var value = parseInt(f,10);
value++;
lastSubTitle = lastSubTitle.substr(0, n.lastIndexOf('[')+1) + value + ']';

alert(lastSubTitle); // alerts "title[0][subtitle][1]"

that should do it.

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.