I have a dynamic form
with huge select lists
instead of querying my database for each select option
. I want to just clone
one row outside my PHP
foreach loop that has the full set of options.
Right now I am doing something like this:
<table id="test" class="table">
<tr>
<td>
<select class="form-control" name="type[]">
<option value="20">Auto Rental</option>
</select>
</td>
<td>
<select class="form-control" name="distance_type[]">
<option value="1">Nearby</option>
</select>
</td>
</tr>
<tr class="clone">
<td>
<select class="readonly form-control" name="type[]" disabled>
<option value="20">Boat Rental 1</option>
<option value="20">Boat Rental 2</option>
<option value="20">Boat Rental3</option>
</select>
</td>
<td>
<select class="readonly form-control" name="distance_type[]" disabled>
<option value="1">Nearby</option>
<option value="1">Far</option>
<option value="1">10 miles</option>
</select>
</td>
</tr>
</table>
<a class="add" href="#">Add New Row</a>
Javascript
$(".add ").on('click', function () {
var clone = $('.clone').closest('tr')[0];
$(clone).clone().insertAfter(clone);
$('.readonly').attr("disabled", false)
});
I disable the select input so it doesn't get submitted unless the "add" button is clicked. The problem is when I click the add button, it ends up enabling it and also adding another field. I pretty much just want to hide the first instance and when clicked it enables it and then when I click add again it adds the new fields, etc.
Here is live version https://jsfiddle.net/f4gp9uky/
Tried some stuff like $('#el'):nth-child(n+3).hide();
But that doesn't work.
Any suggestion would be appreciated.
You can do something like
var $clone = $('.clone'); $(".add ").on('click', function() { if ($clone.hasClass('hidden')) { $clone.removeClass('hidden').find('.readonly').prop("disabled", false) } else { $clone.clone().appendTo($clone.parent()); } });
.hidden { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="test" class="table"> <tr> <td> <select class="form-control" name="type[]"> <option value="20">Auto Rental</option> </select> </td> <td> <select class="form-control" name="distance_type[]"> <option value="1">Nearby</option> </select> </td> </tr> <tr class="clone hidden"> <td> <select class="readonly form-control" name="type[]" disabled> <option value="20">Boat Rental 1</option> <option value="20">Boat Rental 2</option> <option value="20">Boat Rental3</option> </select> </td> <td> <select class="readonly form-control" name="distance_type[]" disabled> <option value="1">Nearby</option> <option value="1">Far</option> <option value="1">10 miles</option> </select> </td> </tr> </table> <a class="add" href="#">Add New Row</a>
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.