The issue is because you only retrieve the val()
of the select when the page loads. You need to get that value when the event occurs, so that it matches what has been selected in the DOM when the user clicks the button.
In addition you need to move the remove()
call to after you append the div
, otherwise the selected option
is removed before it's been read.
Also note that in several instances you're wrapping jQuery objects in another jQuery object. Select your elements once and refer to them as necessary within the event handlers.
Finally, you can look use the length
property to determine how many elements you've appended to the DOM instead of the global x
variable.
This is great, but it will continue to write null when the options run out
This is easily fixed by ensuring that the select had a value.
Try this working example:
$(document).ready(function() {
var max_fields = 26;
var $wrapper = $(".container1");
var $add_button = $(".add_form_field");
var $select = $("#id_100");
$add_button.click(function(e) {
e.preventDefault();
let selectValue = $select.val();
if (!selectValue)
return;
if ($wrapper.children('div').length < max_fields) {
$wrapper.append(`<div><p>ID: ${selectValue} student</p></div>`);
$select.find('option:selected').remove();
} else {
alert('The maximum number of students has been added');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<label for="day">Students</label>
<select name="students_info" class="form-control" id="id_100">
<option value="6">6 || student</option>
<option value="5">5 || student</option>
<option value="4">4 || student</option>
<option value="3">3 || student</option>
<option value="2">2 || student</option>
<option value="1">1 || student</option>
</select>
<input type="submit" name="button" id="submit_button" class="btn btn-success add_form_field" value="Add">
<div class="container1 form-group"></div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…