简体   繁体   中英

Javascript increment number between square brackets

This is my text input box

<input class="tb" id="tb43[0]" type="text" size="30" maxlength="200" />

When cloning with jQuery I'd like the id of the new cloned box to be "tb43[1]" .

$clone.find(".tb").attr("id").replace(/\d+/, function (val) { return parseInt(val) + 1; });

This only increments the first number but how can I manage to increment the number in the square brackets?

Thanks

  1. You can use .attr("id", function() {}) to change the ID. You're currently not altering the ID.
  2. You can alter the regexp to match only in square brackets.
  3. You can use + instead of parseInt (the latter has some caveats).

Eg

$clone.find(".tb").attr("id", function(i, id) {
  return id.replace(/\[(\d+)\]/, function(match, number) {
    // `number` refers to the first group (denoted with ())
    return "[" + (+number + 1) + "]";
  })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM