jQuery preventDefault onclick function - javascript

I have this simple jQuery script that asks to confirm action when you click on a link. And it works great when it's a normal a href link, but I have onclick script assigned to the button and it does not prevent it from firing. I need it to prevent it only once. How can I achieve that?
$(".mybutton").one('click', function() {
event.preventDefault();
$(this).html("Are you sure?");
});
function test() {
$(".forthebutton").html("button click function worked");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="mybutton" onclick="test();">Button</button>
<br /><br /><br />
<span class="forthebutton">button click should change this text</span>

You need to remove original onclick and give it back in this case because you can't influent on onclick handler.
const btn = $(".mybutton");
const onclick = btn.prop('onclick'); // save onclick fn
btn.prop('onclick', null); // remove onclick from button
btn.one('click', function() {
$(this).html("Are you sure?");
btn.on('click', onclick); // add onclick back to button
});
function test() {
$(".forthebutton").html("button click function worked");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="mybutton" onclick="test();">Button</button>
<br /><br /><br />
<span class="forthebutton">button click should change this text</span>

Related

Javascript - strange behaviour naming a function 'submit()'

Is submit a reserved word in Javascript?
Take a look at this code:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="submit()">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
</body>
</html>
I'm trying to understand why I can't call the submit() function inside the <form> tag but it works outside the tag. I think it is a reserved word even because changing the function name the script works well but I can't find any information about that on mdn
I'm not a JS guru, so can someone help me understand this strange behaviour?
The problem is that submit() is a built-in function that gets called whenever a <form> gets submitted. To have custom functionality kick in which a form is submitted, you'll not only need to use a different function name, but also prevent the default form submission with event.preventDefault(), passing the event into the function.
This can be seen in the following -- note that the sayHello() will clear the screen (with an attempted form submission), whereas customSubmit() will not:
<html>
<head>
<script>
function sayHello(){
console.log('Hello!');
}
function customSubmit(e){
e.preventDefault();
console.log('Submit!')
}
</script>
</head>
<body>
<form>
<button onclick="sayHello()">Say hello</button>
<button onclick="customSubmit(event)">Submit</button>
</form>
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="customSubmit(event)">Submit - outside</button>
</body>
</html>
Buttons inside forms automatically submit the form, as long as the button doesn't have an event handler, or has an event handler that doesn't preventDefault():
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
(see how the form gets submitted - the page in the snippet disappears)
It has nothing to do with the submit function name.
But still, using inline event handlers is bad practice and results in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener.
Inline handlers should be avoided just as much as eval should be avoided.
If you want to prevent a button inside a form from submitting the form, call e.preventDefault() like this:
function sayHello(){
console.log('Hello!');
}
function submit(){
console.log('Submit!')
}
const [b1, b2] = Array.from(document.querySelectorAll('button'));
b1.addEventListener('click', (e) => {
e.preventDefault();
sayHello();
});
b2.addEventListener('click', (e) => {
e.preventDefault();
submit();
});
<form>
<button>Say hello</button>
<button>Submit</button>
</form>
Pressing a button in a form reloads the page.
<html>
<head>
</head>
<body>
<!--Any button in the form will submit the form and reload the page-->
<form>
<button id="btn1">Say hello</button>
<button id="btn2">Submit</button>
<button>Anything</button>
</form>
<!--these ones don't-->
<button onclick="sayHello()">Say hello - outside</button>
<button onclick="submit()">Submit - outside</button>
<script>
// notice the page loads when we click the 'anything' button, even without an event handler
//the delay allows you to see it happening
console.log("loading page...");
setTimeout(welcome, 500);
function welcome() {
console.log("page has been loaded");
}
// adding preventDefault to these, stops the form from submitting
function sayHello(e) {
console.log('Hello!');
e.preventDefault();
}
function submit(e) {
console.log('Submit!')
e.preventDefault();
}
//This is how you add event handlers
let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
btn1.addEventListener('click', sayHello);
btn2.addEventListener('click', submit);
</script>
</body>
</html>

jQuery unbind click handler with .off and then rebind with .on

I am trying to prevent a button from being clicked twice by accident by unbinding the click handler with .off like this...
$(".button").click(function () {
console.log("Button has been clicked and disabled");
$( ".button" ).off();
});
$(".button2").click(function () {
console.log("Button has been re-enabled");
$( ".button" ).on();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">
Click Me
</div>
<button class="button2">
Re-enable click
</button>
I am struggling with rebinding it with .on, can anyone point me in the direction of an example or point out what I am doing wrong?
In your click function for button 2, re-enable the first button's click handling with : $(".button").click(buttonOneClick);
Here is an example:
var buttonOneClick = function () {
console.log("Button has been clicked and disabled");
$( ".button" ).off();
};
$(".button").click(buttonOneClick);
$(".button2").click(function () {
console.log("Button has been re-enabled");
$(".button").click(buttonOneClick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">
Click Me
</div>
<button class="button2">
Re-enable click
</button>
Using .one()
using .one() there's no need to use .off() since the event is allowed only once. To re-enable the button you simply re-call the enabling function that does the .one() stuff:
function buttonExec() {
console.log("Button has been clicked and disabled");
}
function buttonEnable() {
console.log("Button has been enabled");
$(".button").one("click", buttonExec); // .one()
}
buttonEnable(); // enable initially
$(".enable").on("click", buttonEnable); // and on ".enable" click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Click Me</button>
<button class="enable">Re-enable click</button>
Using .on() and .off()
function buttonExec() {
console.log("Button has been clicked and disabled");
$(this).off("click"); // .off() since we used .on()
}
function buttonEnable() {
console.log("Button has been enabled");
$(".button").on("click", buttonExec); // .on()
}
buttonEnable(); // enable initially
$(".enable").on("click", buttonEnable); // and on ".enable" click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button">Click Me</button>
<button class="enable">Re-enable click</button>

simulate a click with a key when button is focused

I wan't to simulate a click with a key when the button is focused/active. So, if I move with tab between the buttons and press key "A", the onclick methos should be called. Bellow is my sample code.
Regards!
<script type="text/javascript">
$(document).activeElement(function(e){
if(e.which == 13){
//perform click on a button
}
});
</script>
<button type="button" onclick="alert('you clicked button 1')">button 1 </button>
<button type="button" onclick="alert('you clicked button 2')" >button 2 </button>
Try this:
$('body').on("keydown", "button", function(e) {
if (e.keyCode == 65)
{
$(this).trigger("click");
}
});
Fiddle
You may change the selector for whatever you want, like a class to all elements with the desired behaviour.
To fire events over an element, run the following code template:
element.fire(eventName[, memo]);

Alert On Button Click And Move User To Opened New Tab

I have Created a Button With Link Which opens in new tab. I have also used javascript to alert.
Currently this code is working perfectly. But After Clicking OK in Alert, user stays on same page. But I Want To Move User To New Opened Tab. Is it possible ?
My Code Is -
<form><input type="button" id="anchor1" style="cursor:pointer" value="Click Here" onClick="window.open(href='http://www.google.com')"></form>
<script type="text/javascript">
var anchor = document.getElementById('anchor1');
// or anchor = getElementsByTagName('a') then do ('a')[0]
anchor.addEventListener('click', doSomething, false);
function doSomething() {
alert('You Are About To Open New Tab');
}
</script>
Help Needed
Here Is My
JSFIDDLE
This one is super simple.
You need to remove the onclick attribute from the input tag.
Then, put your code to open new tab using JS after your alert line.
<form><input type="button" id="anchor1" style="padding:5px; cursor:pointer" value="Click Here"></form>
In your JS code, do this:
var anchor = document.getElementById('anchor1');
anchor.addEventListener('click', doSomething, false);
function doSomething() {
alert('You Are About To Open New Tab');
var win = window.open("http://google.com", '_blank');
win.focus();
}
Fiddle
Style the anchor tag by changing the text color to black and changing text-decoration to none:
<button>Click here</button>
HTML
<form><input type="button" id="anchor1" style="padding:5px; cursor:pointer" value="Click Here" ></form>
JS
var anchor = document.getElementById('anchor1');
// or anchor = getElementsByTagName('a') then do ('a')[0]
anchor.addEventListener('click', doSomething, false);
function doSomething() {
alert('You Are About To Open New Tab');
window.open(href='http://www.google.com')
}

How to enable/disable Anchor Tag

Below example is working for enable/disable of href but not for onclick. I need to enable/disable for both attributes
Note: I cant simply remove/bind the onclick event to dummy function() as it need once we enable it.
Script Code:
<script type="text/javascript">
$(document).ready(function () {
$("#b1").click(function () {
$("#yahoo").attr("disabled", "disabled");
$("#yahoo").css("background-color", "silver");
})
$("#b2").click(function () {
$("#yahoo").removeAttr("disabled");
$("#yahoo").css("background-color", "white");
})
$("#yahoo").click(function (e) {
if ($("#yahoo").attr("disabled") == "disabled") {
e.preventDefault();
}
});
});
</script>
HTML Code:
<div>
<input type="button" id="b1" value="Disable Yahoo Link">
<input type="button" id="b2" value="Enable Yahoo Link">
</div>
<a id="yahoo" target="_blank" href="javascript:alert('href alert')" onclick="javascript:alert('onclick alert')">Yahoo.com</a>
Working Example
http://jsfiddle.net/nunnakirankumar/suYe4/
Inside your click() function, you need to explicitly return false (after discovering it's disabled). Otherwise the default handler will cause the browser to go to or run the designated href.
The OP has most likely moved on, so this answer is really just for google searchers' sake.

Categories