Skip to content Skip to sidebar Skip to footer

Can't Call Function On Element After Creating It With Javascript

I 'm using coreUi static template. So I'm manipulating a form. I'm stuck at this form row that should contain websites, originally it contains 1row: input text, input URl, and a c

Solution 1:

The event handler you've got doesn't trigger because the elements you're adding using script didn't exist when the handler was set up.

Use $(document).on("click", ".close", function() { //... . This will add the listener to the whole page instead, but then delegate handling of the event down to elements matching ".close", which do not have to exist when the handler is declared. For more information go to https://api.jquery.com/on/ - read the section "Direct and delegated events".

Solution 2:

when you have element created after DOM rendered, I mean created dynamically you have to take approach of jquery event delegation concept.

$(document).on('click','<selector>',function(){
    //Your code will go here.
    ......
});

Solution 3:

The $('.close').click(...) adds handler to existing close button. But the handler doesn't listen another elements that will be created in future. Use event bubbling instead. Add this handler to parent container using on() method with selector to specify elements that trigger the event:

$('#myform').on('click', '. close', function() {
  close_row();
});

Solution 4:

you should deligate action when dynamically create new div and hide parent.prev elements + clicked button:

<script>
$(document).ready(function(){


$("#add_web_links").click(function(){
                add_web_links();
        });



$('.col-1').delegate("button","click",function(){
$( this ).parent().prevUntil().hide();
$(this).hide();
        });

});


functionadd_web_links()
{
var text="<div class='form-group row web'><label class='col-1 col-form-label'>Text</label><div class='col-2'><input class='form-control' type='text'></div> <label class='col-1 col-form-label'>URL</label>  <div class='col-4'><input class='form-control' type='url'> </div> <div class='col-1'> <button type='button' class='close' aria-label='Close'>   <span aria-hidden='true'>&times;</span></button></div></div>";

$('.web').last().after(text); 
$('.col-1').delegate("button","click",function(){
$( this ).parent().prevUntil().hide();
$(this).hide();
        });  

}

</script><divclass="form-group row"><labelclass="col-1 col-form-label">Text</label><divclass="col-2"><inputclass="form-control"type="text"></div><labelclass="col-1 col-form-label">URL</label><divclass="col-4"><inputclass="form-control"type="url"></div><divclass="col-1"><buttontype="button"class="close"aria-label="Close"><spanaria-hidden="true">&times;</span></button></div></div><divclass="col-6"><buttonid="add_web_links"type="button"class="btn btn-link px-0">add web links</button></div></div><divclass="web"></div>

Post a Comment for "Can't Call Function On Element After Creating It With Javascript"