I have a form with a dropdown. I want to make the dropdown to appear multiple times on click of a button. Like picture below:
If I click “add more student” button, another student’s dropdown should appear.
Here is my code
JavaScript
x
<form_answer id = "more_student" >
<div id ="student_id" class="form-group">
<label class="form-control-label" for="student_id">{{ __('Student') }}</label>
<select type="text" name="student_profile_id" id="student_id" class="form-control">
<option disabled selected> -- select an option -- </option>
@if($student)
@foreach($student as $data)
<option value="{{$data->id}}"> {{$data->student_name}}</option>
@endforeach
@endif
</select>
</div>
JavaScript
<div class = "text-right">
<a class="btn btn-success mt-4" id = "btn_add">Add More Student</a>
</div>
And the script:
JavaScript
<script>
$(document).ready(function(){
$('#btn_add').click(function(){
add_row();
});
});
var id = 0;
function add_row(){
id++;
var html = '<div id ="student_id" class="form-group">' +
'<label class="form-control-label" for="student_id">{{ __("Student") }}</label>' +
'<select type="text" name="student_profile_id" id="student_id" class="form-control">' +
'<option disabled selected> -- select an option -- </option>' +
'@if($student)' +
'@foreach($student as $data)' +
'<option value="{{$data->id}}"> {{$data->student_name}}</option>' +
'@endforeach' +
'@endif' +
'</select>' +
'</div>' ;
$("more_student").append(html);
}
</script>
This code is not working. When I click the button, nothing happens.Can anyone help me with this?
Advertisement
Answer
First you forgot #
before $("#more_student").append(html);
and if you have multiple student_profile_id
then you have to make it array like name="student_profile_id[]"
and every control has unique id
try this one
JavaScript
<script>
var students = eval({!! $student !!});
$(document).ready(function(){
$('#btn_add').click(function(){
add_row();
});
});
function add_row(){
var index = $('input[name="student_profile_id[]"]').length+1;
var html = `<div id="student_div_id`+index+`" class="form-group">
<label class="form-control-label" for="student_id">{{ __("Student") }}</label>'
<select type="text" name="student_profile_id[]" id="student_id`+index+`" class="form-control">
<option disabled selected> -- select an option -- </option>`;
$.each(students,function(ind,el)){
html+=`<option value="`+el.id+`"> `+el.student_name+`</option>`;
});
html+=`</select>
</div>`;
$("#more_student").append(html);
}
</script>