I am trying to check if a button was clicked or not using jquery.
this is my snippet in the javascript section of my code
window.onbeforeunload = function() {
jQuery(':button').click(function () {
if (this.id == 'click') {
alert('this button was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
};
this is the button I am using to test the function
<button id="click">save</button>
on clicking the button nothing happens. please kindly assist
I am trying to check if a button was clicked or not using jquery.
this is my snippet in the javascript section of my code
window.onbeforeunload = function() {
jQuery(':button').click(function () {
if (this.id == 'click') {
alert('this button was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
};
this is the button I am using to test the function
<button id="click">save</button>
on clicking the button nothing happens. please kindly assist
Share Improve this question asked Apr 10, 2017 at 14:17 parkerparker 2653 gold badges6 silver badges21 bronze badges 3-
jQuery('button')
– andrepaulo Commented Apr 10, 2017 at 14:19 - So you are binding the event after it was clicked.... – epascarello Commented Apr 10, 2017 at 14:19
-
Why are you setting a click handler in
onbeforeunload
? When that event is happening, isn't clicking a button pretty much out of the question thereafter? What are you actually trying to acplish here? – David Commented Apr 10, 2017 at 14:22
4 Answers
Reset to default 2The Events triggered by the button are given on jQuery Code load so you need to place it in a $(document).ready()
This will work for you:
$(document).ready(function(){
$("#click").click(function(){
//do stuff
});
})
here you directly adress the id of the button your html would look like:
<button id="click">save</button>
which is actually the same :D
Try the following way:
jQuery(document).ready(function(){
jQuery(':button').click(function () {
if (this.id == 'click') {
alert('this button was clicked');
}
else if (this.id == 'button2') {
alert('Button 2 was clicked');
}
});
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click">save</button>
<button id="button2">button2</button>
You are binding the event after it was clicked. When the onbeforeevent has already fired, the click has happened.
You need to bind it outside of that event.
jQuery(function(){
window.onbeforeunload = function() {
console.log(clicked);
};
var clicked = null;
jQuery('button').on("click", function () {
clicked = this.id;
});
});
var clickedButtons = [];
$('button').on('click', function(){
if($.inArray($(this).attr('id'), clickedButtons){
console.log('button allready clicked once');
} else {
clickdeButtons.push($(this).attr('id'));
}
});
this solution can handle more than one button
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744307645a4567793.html
评论列表(0条)