Reputation: 115
I try to write select box with dynamically adding and deleting values. I can add values but unfortunately I can't delete it. Here is code;
<ul class="subscribe" style="text-align: center;">
<li class="container-box">
<span class="input-text">name</span>
<input type="text" name="name-surname" id="add-name" class="adding-name" style="color: #000;"/>
<li class="container-box">
<span class="input-text">birth day</span>
<select name="day" id="day">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="month" id="month">
<option value="september">September</option>
<option value="october">october</option>
</select>
<select name="year" id="year">
<option value="2016">2016</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
</select>
</li>
<li>
<button class="adding-selectbox">add</button>
</li>
<li class="adding-b-day">
</li>
</ul>
Javascript
$(".adding-selectbox").on('click', function(event) {
event.preventDefault();
var getvalue = $("#add-name").val();
var babyDay = $("#day").val();
var babyMonth = $("#month").val();
var babyYear = $("#year").val()
var allBabyValues = getvalue + " / " + babyYear + "-" + babyMonth + "-" + babyDay;
$('.adding-b-day').append("<div class='select-element'><select name='child-name[]' id='select-attrs'><option value="+ allBabyValues +">"+allBabyValues +"</option></select></div>");
$('.select-element').append('<span class="delete-selectbox">x</span>');
});
$(".delete-selectbox").on("click", function() {
var select = $(".select-element");
select.remove();
});
I try so hard and my codes goes nowhere at this time. I just want to do each add button gives new select and new options and it must be delatable. what would you recommend to do I'am? Thank you...
Upvotes: 0
Views: 149
Reputation: 4401
Bind the listener to delete on BODY and not the button itself because at the time of binding the button doesn't exist. When you bind to body it works even if the element was added later.
Change
$(".delete-selectbox").on("click", function() {
to
$("body").on("click", '.delete-selectbox',function() {
Upvotes: 1