I have an html as follows:
<fieldset id="question1">
<legend class='legend'>...</legend>
...
<input type="text" name="label_no1" id="label_no1" autocomplete="off">
</fieldset>
On the java script, I’m cloning the fieldset, yet I want to access its element to change ids, and some of the text.
I tried this and it did not work:
$('#question1").siblings(".legend").html="any text"; \\ I also tried children
I also want to be able to access all the inputs inside the fieldset, so to change their ids.
Any help?
To clone the fieldset and add it to the same parent:
Note we’re changing the ID before adding it to the tree, since you can’t have two elements with the same ID.
To do things with the elements within it, you can use
.children()or.find()on yourclonevariable with a selector to select the children/descendants you want (once you’ve added the clone to the parent). For instance, to clean up theids on the inputs:Note that within the
eachcallback,thisis not a jQuery instance, it’s the raw element. (Hence my settingthis.iddirectly.) If you wanted to get a jQuery instance for the element, you’d dovar $this = $(this);and then use$this.attr("id", ...)instead. But there’s no particular need unless you’re doing something other than changing the ID.Answering your question about renumbering IDs, you’ll need to be sure you update whatever’s using those IDs as well as the actual IDs on the input elements.
But in terms of doing the update on the input elements, you could do it by reading the number and incrementing it until you get one that isn’t used:
…which will give you “input_radio2” if the original ID was “input_radio1”, but I think I’d probably use a different naming convention instead. For instance, you could prefix your various input IDs with the ID of the question:
…and then just replace ‘question1’ with ‘question2’ in the cloned IDs. (Colons [
:] are perfectly valid in IDs.)If you can avoid having IDs on all of your inputs, though, that would be the way to go. For instance, unless your markup prevents it for a different reason, you can associate an
inputwith itslabelvia containment rather than usingfor:Lots of options. 🙂