Reputation: 214
I'm currently able to append HTML and remove the right appended HTML, but when I add more of that HTML it is appended with the same id so the functionality if I want to show or hide a certain div element, is not working.
This is the code that i append and remove:
$(".adRowOutdoor").click(function(){
var newTxt = $('<div class="add-row-outdoor row width-100 padding-left-15"> <div class="form-group col-md-4"> <label for="state" class="control-label">Type</label> <div class="sg-select-container"> <select id="choose-outdoor"> <option disabled="">Choose type</option> <option value="Undercover walkway">Undercover walkway</option> <option value="Oval">Oval</option> <option value="Swimming Pool">Swimming Pool</option> <option value="Outdoor Basketing Court">Outdoor Basketing Court</option> <option value="other">Other</option> </select> </div> </div><!-- end col --> <div id="choose-outdoor-is-hidden" class="form-group col-md-4" style="display: none;"> <label for="other-textfield" class="control-label">Other</label> <input type="text" class="form-control form-input-field" name="other-textfield" value="" required="" placeholder=""> <span class="help-block"></span> </div> <div class="col-md-2 remove-btn-audit form-space-top-35"> <button class="btn btn-add-waste removeOutdoor"><i class="fa fa-minus-circle o-btn-add" aria-hidden="true"></i>Remove</button> </div> </div><!-- row audit -->');
$(".row-outdoor-container").append(newTxt);
});
$("body").on('click' , '.removeOutdoor' , function(){
var curRow = $(this).parents('div.add-row-outdoor');
curRow.remove();
});
What I want now is to hide and show a div element with a text field on the selection of the certain div with a unique id that I want to generate.
I'm able to show that text field only for the first element, but not for other appended HTML.
$('#choose-outdoor').change(function (e) {
var val = $("option:selected", this).val()
if (val == 'other') {
$('#choose-outdoor-is-hidden').show();
}
// Hide complete sub type div
else {
$('#choose-outdoor-is-hidden').hide();
}
});
JsFiddle of my code is here
Upvotes: 1
Views: 1251
Reputation: 36703
Change id
to classes
so basically make choose-outdoor
and choose-outdoor-is-hidden
as your classes on the same elements.
Then use event delegation as the elements are dynamically created:
$('.row-outdoor-container').on("change", '.choose-outdoor', function (e) {
var val = $(this).val();
$el = $(this).closest(".add-row-outdoor").find('.choose-outdoor-is-hidden');
if (val == 'other') {
$el.show();
}
else {
$el.hide();
}
});
Updated fiddle
Upvotes: 2