Saturday, 31 August 2013

Append to a div with a recurring class

Append to a div with a recurring class

I have a piece of JS that appends the following to a web form on the click
of a button. When the div .remove is clicked the closest new-attribute div
is removed. It works fine.
<div class="new-attribute">
<h3>New Attribute</h3>
<label for="attributeName3">Name:</label>
<input class"attribute"="" type="text" name="attributeName3">
<label for="attributeType3">Type:</label>
<select id="t" class="attribute" name="attributeType3">
<option value="text" selected="">Text</option>
<option value="checkbox">Checkbox</option>
<option value="select-list">Select Option List</option>
<option value="notes">Notes</option>
</select>
<div class="option"></div>
<div class="remove">Delete</div>
</div>
In the div "option" I have code to add another form field on the selection
of "select-list" in the select input. It does not work. I do not know why.
No variable names are clashing. I'm away I shouldnt give the select an id
because it is recurrent, I just want to get it working before I make it
compliant.
Heres the Js that I'm having trouble with:
//select temp
var select="<div class=\"new-option\">"
+ "<h3>new option</h3>"
+ "<label for=\"attributeName"+count+"\">New otion:</label>"
+ "<input class\"attribute\" type=\"text\"
name=\"attributeName"+count+"\">"
+ "</div>";
//get value of select
$('#t').change(function() {
var selectVal = $('#t :selected').val();
if (selectVal == "select-list") {
$(this).closest('.option').append(select);
}
});
The code works with $(select).appendTo('.option'); However it appends the
code to every instance of the "option" class on the page. I only want it
to append to the current or closest one.
Thank you in advance

No comments:

Post a Comment