I want to disable click property after I click once - javascript

**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>

Related

How to prevent or disable the event handling of a button's click depending on a text-input's value?

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>

Change text inside a button on each click using javascript?

I need to change text each time I click on button.
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("data-text") == button.innerHTML) {
button.innerHTML = button.getAttribute("data-text1");
} else {
button.setAttribute("data-text1", button.innerHTML);
button.innerHTML = button.getAttribute("data-text");
}
},
false
);
<div>
<button id="changeText" data-text="Show" data-text1="Hide">Hide</button>
</div>
I don't understand why this code doesn't work when I try to load page using google chrome. However when I loaded it to codepen it worked
It expects from you certain structure like this one:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText" text="Show" >Hide</button>
</div>
<script>
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.getAttribute("text") == button.innerHTML) {
button.innerHTML = button.getAttribute("text1");
} else {
button.setAttribute("text1", button.innerHTML);
button.innerHTML = button.getAttribute("text");
}
},
false
);
</script>
</body>
</html>
Copy paste it to your file and you'll see that it works.
Please mark it as an answer if it fixes your problem :)
Your code is working, but your approach is not so nice. See the 2 options down below.
let text = {
'Hide': 'Show',
'Show': 'Hide'
}
const click = (event) => {
// option 1, it needs the object above.
// It's good for multiple alternatiosn like color, icon etc
// or multiple states like hide to show, show to sure, sure to really, really to hide.
event.target.innerText = text[event.target.innerText];
// option 2, it's good for one or two alternations.
// event.target.innerText = event.target.innerText == 'Hide' ? 'Show' : 'Hide'
}
document.querySelector('button').addEventListener('click', click);
<button>Show</button>
you can make it more simple by removing the custom attribute and use the button innerHTML only along with enum by using Object.freeze(),it will make the code more readable
const titleEnum = Object.freeze({show: "SHOW", hide: "HIDE"});
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (button.innerHTML === titleEnum.hide) {
button.innerHTML = titleEnum.show;
} else {
button.innerHTML = titleEnum.hide;
}
},
false
);
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div>
<button id="changeText">HIDE</button>
</div>
</body>
</html>
Use innerText to get the value of an element
const changeBtn = document.getElementById("changeText");
changeBtn.addEventListener("click", ()=>{
if(changeBtn.innerText === "2"){
changeBtn.innerText = "1";
}
else{
changeBtn.innerText= "2";
}
});
<div>
<button id="changeText">1</button>
</div>

Stop onclick event, once onblur event got active

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>

Enable and Disabling a JavaScript code

I have a JavaScript code and what I would like to do with it is to enable and disable the JavaScript code with a button.
So when I press the button the JavaScript code is enable, then press it again and it is disabled.
I don't want to Enable / Disable JavaScript itself. But just the code inbetween <script></script>
It would be controlled by a bool so, true / false.
I hope you can understand what I am trying to say. :P
You can do toggle the value of a hidden variable onClick of the button
and in the <script>, you can check the value of the hidden variable
For eg:
<input type='hidden' name='js_enabled' value='1' />
<button name='toggle_js' onClick='toggle()'>Toggle</button>
<script>
function toggle() {
if (document.getElementByName('js_enabled').val == 1) {
document.getElementByName('js_enabled').val = 0
} else {
document.getElementByName('js_enabled').val = 1
}
}
if (document.getElementByName('js_enabled').val == 1) {
//your functions here
}
</script>
Just set a global variable and check its value inside every function.
<script type="text/javascript">
window.runScripts = true;
function enableScripts() { window.runScripts = true; }
function disableScripts() { window.runScripts = false; }
function func_1() {
if (window.runScripts) { /* run your code */ }
}
function func_2() {
if (window.runScripts) { /* code for function 2 */ }
}
// ....
</script>

Detecting change in hidden form field

Im writing a test code to do a counter that stores the value in a hidden form field. Whenever this counter is incremented with a button click, the counter value is stored in the hidden field. I have no problem with this portion.
However, im having problem to display an alert whenever the hidden field is being changed. Pls see my code below and tell me where i have gone wrong. Thank You.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
storage=document.getElementById('store').value;
alert(storage)
}
$(document).ready(function() {
var content = $('#store').val();
$('#store').change(function() {
if ($('#store').val() != content) {
alert('Content has been changed')
}
});
});
</script>
</head>
<body>
<input type="button" id="trigger" value="Start" onclick="startRolling()"/>
<input type="text" id="cnt" readonly="readonly"/>
<input type="hidden" id="store" value="0"/>
</body>
What if you just fire the event without trying to detect the change?
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
if(storage != tonum) {
alertChange();
}
//storage=document.getElementById('store').value;
//alert(storage)
}
function alertChange() {
alert('Content has been changed');
}
You could also look at the trigger event in jquery: http://api.jquery.com/trigger/.
Try this
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
//storage=document.getElementById('store').value;
//alert(storage)
}
$(document).ready(function() {
//var content = $('#store').val();
$('#store').change(function() {
//if ($('#store').val() != content) {
alert('Content has been changed')
}
});
Why don't you change the first function to jquery?
From the description of the change-event:
The change event occurs when a control loses the input focus and its value has been modified since gaining focus.
Hidden inputs cannot lose focus(because they never have focus), so change will not fire there anyway.
See Any even to detect when the "Class" attribute is changed for a control for a solution.
Rather than using a change event, I've used a loop event that checks every second.
var content="";
function startRolling() {
var storage=document.getElementById('store').value;
var tonum;
if(parseInt(storage)==0)
{
tonum=1;
}
else {
tonum=parseInt(storage,10);
}
tonum=tonum+1;
document.getElementById('store').value=tonum;
storage=document.getElementById('store').value;
content=storage;
alert(storage)
}
function checkifchanged(){
if ($('#store').val() != content) {
alert('Content has been changed');
}
else{
content = $('#store').val();
}
setTimeout('checkifchanged()',1000);
}
$(document).ready(function() {
content = $('#store').val();
checkifchanged();
});
var content = $('#store').val();
You are storing the changed value and comparing with the same value,
this if statement doesn't execute
if ($('#store').val() != content)
don't store the value just call change event directly.
$(document).ready(function() {
$('#store').change(function() {
alert('Content has been changed')
});

Categories