I have one text field and one button, I just want to ignore onclick event on button, when onblur events got activated. I tried a few methods but didn't work for me.
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction(event)">
<button onclick="calldiv(event)">Click</button>
<script>
function myFunction(event) {
// event.preventDefault();
// event.stopPropagation();
// event.stopImmediatePropagation();
console.log("blur");
}
function calldiv(event) {
console.log("div");
}
</script>
</body>
</html>
Result...
1st time button got clicked:-blur
2nd time button got clicked:-div
an easy way to solve it is to make an if statement inside calldiv function
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction(event)" />
<button id="button" onclick="calldiv(event)">Click</button>
<script>
let blured = false;
function calldiv(event) {
console.log(blured);
if (!blured) {
console.log("div");
} else {
blured = false;
}
}
const currentButton = document.getElementById("button");
function myFunction(event) {
console.log("blur");
blured = true;
}
</script>
</body>
Related
I have a 'onChange' event on a text field, that check some condition.
$(document).ready(function() {
$('#txt').on('change', (ev) => {
if ($(ev.target).val() == "stop") {
console.warn("Wrong condition, I want to avoid the click event on button");
alert("Wrong condition, no click on button");
} else {
console.log("Condition OK!");
}
});
$('#btn').on('click', (e) => {
console.log("Button pressed");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input id="txt"/>
<button id="btn">Click me</button>
</div>
What I like to have is that, when I type 'stop' on the field and then click the button, the button's click triggers the onChange and the onChange event should prevent the click event execution.
With the alert() this works, but I want it works without the alert() too.
Is it possible?
Switching the text-field and button validation-handling from a 'change' to an 'input' event does support a brute force approach which disables/enables the button upon the OP's condition. The latter btw got changed as well from the value having to equal 'stop' to a value that just has to contain/include the substring 'stop' regardless of its letter-casing.
$(document).ready(function() {
// ... switching from 'change' to 'input' event
// does support the following brute force approach ...
$('#txt').on('input', (ev) => {
if ($(ev.target).val().toLowerCase().includes("stop")) {
// "Wrong condition, I want to avoid the click event on button"
// ... disabling the button is one possible way ...
$('#btn')[0].disabled = true;
} else {
$('#btn')[0].disabled = false;
}
});
$('#btn').on('click', (e) => {
console.log("Button pressed");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input id="txt"/>
<button id="btn">Click me</button>
</div>
A proper generic implementation of the above approach and code into vanilla JS then might look as follows ...
function handleComponentButtonClick(evt) {
const elmButton = evt.currentTarget;
const elmInput = elmButton.previousElementSibling;
console.log({ currentClickRelatedValue: elmInput.value });
}
function handleComponentButtonState(evt) {
const elmInput = evt.currentTarget;
const elmButton = elmInput.nextElementSibling;
elmButton.disabled = elmInput.value.toLowerCase().includes('stop');
}
function enableInputAndButtonComponentBehavior(elmButton) {
const elmInput = elmButton.previousElementSibling;
elmInput
.addEventListener('input', handleComponentButtonState);
elmButton
.addEventListener('click', handleComponentButtonClick);
}
function main() {
document
.querySelectorAll('.container [type="text"] + button')
.forEach(enableInputAndButtonComponentBehavior);
}
main();
.container { float: left; margin: 0 20px; }
<div class="container">
<input type="text" />
<button>Click me</button>
</div>
<div class="container">
<input type="text" />
<button>Click me</button>
</div>
Let's say I have an input
<input type="text" id="inPut" autofocus>
and a button
<button id="btn">Some text</button>
I want that onblur, it loses focus (as it normally would), but when I click this button, nothing happens to the focus i.e it does not lose focus
You can use JS to focus the input on button click.
const btn = document.querySelector("#btn");
const inp = document.querySelector("#inp");
btn.addEventListener("click", () => {
inp.focus();
});
<input id="inp" type="text">
<button id="btn">Click</button>
If you don't want the input to focus on click if it is not already focused.
You can store input's focus information in a variable, toggle that variable on button's mouseover event (this would work because mouseover fires before click and mouseover doesn't make the button active)
const btn = document.querySelector("#btn");
const inp = document.querySelector("#inp");
let isInputFocused = false;
btn.addEventListener("mouseover", () => {
if (inp === document.activeElement) {
isInputFocused = true;
} else {
isInputFocused = false;
}
});
btn.addEventListener("click", () => {
if (isInputFocused) {
inp.focus()
}
});
<input id="inp" type="text">
<button id="btn">Click</button>
**I want to disable clickability after the first click ** I used this code but did not work.
let counter = 0;
inputOptions.forEach((inputOptions) => {
inputOptions.addEventListener("click", () => {
inputOptions.classList.toggle("active");
if (inputOptions.classList.contains("active")) {
inputOptions.style.pointerEvent = 'none';
}
if (inputOptions.innerHTML == "Dhaka") {
counter++;
} else { counter = 0; }
})
})
function getResult() {
document.getElementById("result").innerHTML = "No of Correct answer:" + counter;
}
you can pass parameter { once: true }
document.querySelectorAll('button').forEach((inputOptions) => {
inputOptions.addEventListener("click", (el) => {
console.log(inputOptions)
}, { once: true })
})
<button>A</button>
<button>B</button>
here is sample of code for disabled button after once click.
You need to define id in html then access button like below code.
this is just sample of working code. you need to get idea from this then implement according to your requirement
<html>
<head>
<title>JavaScript - Disable Button after Click using JavaScript Function.</title>
<script type="text/javascript">
function disableButton(btn){
document.getElementById(btn.id).disabled = true;
alert("Button has been disabled.");
}
</script>
</head>
<body style="text-align: center;">
<h1>JavaScript - Disable Button after Click using JavaScript Function.</h1>
<p><input type="button" id="btn1" value="Click to disable button." onclick="disableButton(this)"</p>
</body>
</html>
I have one function and I need to start in on click or on pressing Enter key.
So I'd need something like:
<BUTTON onclick="searchProduct()" or onkeypress="searchProduct()">Hledat</BUTTON>
But only on pressing Enter. Not on any key.
Is this possible for Ajax or plain javascript?
OK, didn't expect that it is so complicated, so I give you whole of my code, because your answers are not working for my whole code...
<!DOCTYPE html>
<HTML>
<HEAD>
<META charset="UTF-8" />
<TITLE>Searchin engine</TITLE>
</HEAD>
<BODY>
<SCRIPT src="js_search.js"></SCRIPT>
<FORM>
<INPUT type="text" id="word" size="40" />
</FORM>
<BUTTON onclick="searchProduct(document.getElementById('word').value)">Hledat</BUTTON>
<P id="display"></P>
</BODY>
</HTML>
Just add event listeners in your javascript (above your searchProduct() function, for instance)
document.getElementById('button').addEventListener('click', function(){
searchProduct(document.getElementById('word').value);
})
document.getElementById('button').addEventListener('keydown', function(e){
if(e.keyCode == 13) searchProduct(document.getElementById('word').value); // the keyCode 13 is equivalent to the enter key
})
function searchProduct(val) {
alert(val);
}
<button id="button">Hledat</button>
<input id="word" value="foo"/>
Hope this helps!
Ideally, you should have individual events on element and enter, you can either call specific function or you can trigger element's click.
If you wish enter and button click work same, I would suggest to trigger click event. This will make sure all UI states are updated and all processing are done. Reason for this is, we can add multiple handlers to a button for different processing and calling functions might not call other code.
function keyPress(e) {
if (e.keyCode == 13) {
document.getElementById("btn").click();
}
}
function notify() {
console.log("Processing...")
}
<input type="text" id="txt" onkeyup="keyPress(event)">
<button id="btn" onclick="notify(event)">Notify</button>
You can do:
<BUTTON onclick="searchProduct()" onkeypress="searchProductKeyPress(event)">Hledat</BUTTON>
function searchProductKeyPress(event) {
if (event.which == 13 || event.keyCode == 13) {
searchProduct();
return false;
}
return true;
}
In the function you can pass the event like this:
<BUTTON onclick="searchProduct(event)" onkeypress="searchProduct(event)">Hledat</BUTTON>
Now in the function:
searchProduct(e){
if(e.type === 'keypress' && e.keyCode !== 13){
return;
}
// put the code for search here.
}
set id="btn_search_product" to your button
var btn_search_product = document.getElementById("btn_search_product");
btn_search_product.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
searchProduct(e);
}
});
I actually use evento library https://github.com/petermichaux/evento
with it it would be:
evento.add(btn_search_product, "keydown", function (e) {
if (e.keyCode === 13) {
searchProduct(e);
}
});
My code works with 'Onclick'. I need it to work with onBlur mode in JavaScript.
My code
if(!m.isSystemButtonClicked)
{
console.debug("Inside onHide. m.isSystemButtonClicked=",m.isSystemButtonClicked);
if(m.unloadListener)
{
window.onbeforeunload = m.unloadListener;
}
}
onblur Event syntax
In HTML:
<element onblur="myScript">
In JavaScript:
object.onblur=function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("blur", myScript);
example :
source - http://www.w3schools.com
<!DOCTYPE html>
<html>
<body>
<p>When you enter the input field (child of FORM), a function is triggered which sets the background color to yellow. When you leave the input field, a function is triggered which removes the background color.</p>
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow";
}
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = "";
}
</script>
</body>
</html>
Your example can be rewritten as
m.onblur = function() {
console.debug("Inside onHide. m.isSystemButtonClicked=",m.isSystemButtonClicked);
if(m.unloadListener)
{
window.onbeforeunload = m.unloadListener;
}
}