I have a web application in which the user can add household names dynamically and delete those name if they want to.
In my view:
<tr>
<td>Add Household</td>
</tr>
<tr>
<td>
<div class="field_wrapper">
<div>
<select name="field_name[]" value="" id="drop2" style="color:black;">
<?php
foreach ($head as $row) {
echo "<option style='color:black;' value='".$row['hh_id']."'>".$row['hh_fname']." ".$row['hh_lname']."</option>";?>
</select>
<a href="javascript:void(0);" class="add_button" title="Add field"><img src="<?php echo base_url('dist/img/add-icon.png'); ?>" /></a>
</div>
</div>
</td>
</tr>
Script:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><select name="field_name[]"><option></option></select><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="<?php echo base_url("dist/img/remove-icon.png"); ?>" /></a></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
I want that whenever the user clicks the add
button, the same dropdown should be shown like the first dropdown displayed. How should I achieve that in the script part? How to populate the fieldHtml
to dropdown then?
The add
and remove
functions worked well. It's just that whenever there will be an addition, it should show the dropdown.
Thank you a lot for your help.
There is a workaround that may help you. Instead of wanting to re-open the drop-down you can go for a multiple row select:
<select name="field_name[]" value="" id="drop2" style="color:black;" size="10">
With the size
attribute on your select
tag you will not have the popover drop-down but you will have a drop-down like element always visible.