Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery Replace DIV data and then track clicks on it

I have a <div id="myContainer"></div> . I also have a button: <input type="button" value="Send" id="sendButton"> While clicking at the button: it replaces the DIV with another:

$( "#sendButton" ).click(function() {
$( "#myContainer" ).replaceWith("<div id='calc'><input type=\"text\" id=\"screen\" value=0><button id=\"add\">+</button><button id=\"mul\">*</button><button id=\"settings\">settings</button><button id=\"clear\">clear</button></div>");
});

I want to activate another function after click on a new button I've just put (<button id=\"mul\">*</button>):

$( "#mul" ).click(function() {
console.log(' mul clicked!');
});

Which doesn't work, the fact that I'm waiting for a click on a div that just created have something to do with it?

like image 912
fgfjhgrjr erjhm Avatar asked Jan 18 '26 19:01

fgfjhgrjr erjhm


2 Answers

You need to attach event to #mul. Because it is appended dynamically, $("#mul").click() will not work.

.on() attaches event handlers to the currently selected set of elements.

Try:

$("body").on("click","#mul",function(){
    console.log("mul clicked!");
});

More information here.

like image 184
codingrose Avatar answered Jan 20 '26 09:01

codingrose


When you call $( "#mul" ).click(), you're attaching an event handler to #mul as it exists at that point. To fix this, just call $( "#mul" ).click() after you create #mul.

$( "#sendButton" ).click(function() {
    $( "#myContainer" ).replaceWith("<div id='calc'><input type=\"text\" id=\"screen\" value=0><button id=\"add\">+</button><button id=\"mul\">*</button><button id=\"settings\">settings</button><button id=\"clear\">clear</button></div>");
    $( "#mul" ).click(function() {
        console.log( ' mul clicked!' );
    });
});

You could also use jQuery's .on method with the optional selector, called a delegated event handler according to the documentation. Take a look at the API for jQuery if that's what you want: jQuery API documentation. The basic usage would be something like

$( document ).on( "click", "#mul", function( ) {
    console.log( ' mul clicked!' );
});
like image 22
Matthew Avatar answered Jan 20 '26 08:01

Matthew