Msg onclick event alert event
I'm trying to trigger a click on a button from a .cshtml file:
<input type="button" id="ImageHosting" value="To Image Hosting" onclick="ImageHosting_Click()"/>
This is the .js file:
function ImageHosting_Click() {
$("#ImageHosting").click(function () {
alert("test");
});
}
I can't get the warning message. Any idea why?
+3
source to share
3 answers
// Try like this:
$("#ImageHosting").click(function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="ImageHosting" value="To Image Hosting" />
+6
source to share
You are binding an inline event handler in HTML, also you are using jQuery to re-bind inside the function which is wrong.
Just remove the inline onclick,
<input type="button" id="ImageHosting" value="To Image Hosting" />
And change the JS
$(document).ready ( function () {
$("#ImageHosting").click(function () {
alert("test");
});
});
If this button is inserted dynamically,
$(document).ready ( function () {
//replace document below with enclosing container but below will work too
$(document).on('click', "#ImageHosting", function () {
alert("test");
});
});
Use .live/.delegate
if older jQuery version (<1.7)
+5
source to share
Conversely, the answer from SKS (supporting inline attribute onclick
) is:
<input type="button" id="ImageHosting" value="To Image Hosting" onclick="ImageHosting_Click()"/>
and
function ImageHosting_Click(){
alert("test");
}
Or even all in one:
<input type="button" id="ImageHosting" value="To Image Hosting" onclick="alert('test');"/>
+4
source to share