Reputation: 365
I am trying to invoke a button click from inside 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 am not able to get the alert message. Any idea why?
Upvotes: 3
Views: 86203
Reputation: 845
// 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" />
Upvotes: 5
Reputation: 7866
Conversely to SKS's answer (keeping the inline onclick
attribute):
<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');"/>
Upvotes: 6
Reputation: 79830
You are binding the event handler inline in HTML also you are using jQuery to bind again inside the function which is not correct.
Just remove the inline onclick,
<input type="button" id="ImageHosting" value="To Image Hosting" />
And change JS
$(document).ready ( function () {
$("#ImageHosting").click(function () {
alert("test");
});
});
Incase if this button is inserted dynamically then,
$(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 you older version of jQuery ( < 1.7)
Upvotes: 6