I saw this post for cloning form fields with incrementing ids - works great.
But, in my adaptation, I have added a select box in the cloned form. The select box's id increments as it should. The goal is that when a particular choice (always the same in every cloned field) is selected, some hidden inputs are revealed.
I can do this with javascript for a set # of known select elements, but I can't figure out how to iterate of each cloned select
, since the user can create as many as they need?
A simple version is thus:
HTML
<div id="zero_form" style="display:none;">
<p>
<input id='box1_' type="text" style="width:125px" placeholder='Type'>
<br>
<select id='box2_' class="first_input" style="width: 200px;" placeholder="Choose a Value">
<option value="Choose a Value">Choose a Value</option>
<option>NEGATIVE</option>
<option>EQUIVOCAL</option>
<option>POSITIVE</option>
</select>
<input id='box3_' style='display:none;' placeholder='Score #1'>
<input id='box4_' style='display:none;' placeholder='Score #2'>
<input id='box5_' style='display:none;' placeholder='%'>
<input id='box6_' type="text" placeholder="Enter Comments" style="width:200px">
<input type="button" id="remove" class="removebutton" value="Delete">
<br>
</p>
</div>
<!-- end hidden clone div-->
<form>
<p>
<span id="add" class="addbutton">Add another row</span>
</p>
</form>
jQuery
$(document).ready(function () {
// show hidden inputs on POSITIVE selection
$('input [type=select]').each(function(){
var sel = $(this).val();
if (sel == 'POSITIVE'){
$(this).parent().find('[type=text]').show();}
else {
$(this).parent().find('[type=text]').hide();}
});
// clone fields
var form_index = 0;
$("#add").click(function () {
form_index++;
$(this).parent().before($("#zero_form").clone().attr("id", "zero_form" + form_index));
$("#zero_form" + form_index).css("display", "inline");
$("#zero_form" + form_index + " :input").each(function () {
$(this).attr("id", $(this).attr("id") + form_index);
});
$("#remove"+form_index).click(function () {
$(this).closest("div").remove();
});
});
});
There is something I'm not understanding about the syntax within my each
function? Help please!
to make element access easier, I have made some dom changes also - added some class attributes
Choose a Value NEGATIVE EQUIVOCAL POSITIVE
Add another row
then
Demo: Fiddle