Disable more than one button with a click - javascript

I have 4 answer buttons that trigger a tick or a cross to be displayed depending on whether the answer is right or not ("showDiv01"/"showDiv02"), I want to disable all of the buttons after any of them are clicked, so far I can only disable the button that is clicked with "onClick=this.disabled = 'true';".
<button id="none" onClick="showDiv01(); this.disabled = 'true';">Almond White</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">Raspberry Diva</button<br>
<button id="none" onClick="showDiv01(); this.disabled = 'true';">Melon Sorbet</button><br>
<button id="none" onClick="showDiv01(); this.disabled = 'true';">Gentle Lavender</button><br>
Any solutions?

I would recommend adding a common class to your buttons (for this example, say you btnClass as your class), also, you can use the same function for each button click, no need to create unique functions for buttons doing the same type of behavior:
function showDiv(el) {
//"el" should be "this" passed in to the func
var buttons = document.getElementsByClassName("btnClass");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
<button id="none" onClick="showDiv(this)"></button>
With this passed in, you have direct access to the element being clicked through the el param in the function. So el.id will result in the ID of the clicked element.

You have showDiv01(); function called on click also. Put there code to disable buttons finding them by id.
Besides I don't think you can have same id for different buttons like "none", I would also consider keeping answer somewhere else than button id.
I would pass some parameter to showDiv01(); function like showAnswerDiv(1); or showAnswerDiv(2);.
This way you could take action based on parameter which is a lot better than making function for valid or invalid answer and pinning it to button.

Related

How to Disable two buttons when only one is clicked in javascript without the use of Jquery

I currently have two buttons. I want when one button is clicked both of the buttons get disabled. I want to use only javascript without Jquery.
var button1=document.getElementById("button1").addEventListener('click',function(){
//I want to check if either of the buttons were clicked and disable both of them.//
if(button1||button2===true){
button1.disable=true;
button2.disable=true;
Alert("Button Disable property is in a true state.");
}
});
var button2=document.getElementById("button2").addEventListener('click',function(){
//I want to check if either of the buttons were clicked and disable both of them.//
if(button1||button2===true){
button1.disable=true;
button2.disable=true;
Alert("Button Disable property is in a true state.");
}
});
//I also tried to set the {once : true;} at the end of the event handler but it only works for one button.Which means that I have to press both of them tfor them both to disable.//
<button id="button1">Button1</button>
<button id="button2">button2</button>
You have a number of problems. Firstly, your variables are being set to the return value of addEventListener, not the document element. Secondly, to disable an element, you use element.disabled = true, not element.disable = true. Finally alert is all lowercase, not Alert. There are also optimisations that can be made to your code - for example there is no need to check if button1 or 2 was clicked since if the event listener is called then one of them must have been. Try this instead:
var button1=document.getElementById("button1");
var button2=document.getElementById("button2");
[button1,button2].map(b => b.addEventListener('click',function(){
button1.disabled=true;
button2.disabled=true;
alert("Button Disable property is in a true state.");
}));
<button id="button1">Button1</button>
<button id="button2">button2</button>

Trigger checkbox change event with plain javascript (NOT jQuery)

I'm building a multiple select with ES6. It's all up and functional (moving trough items, clicking them, highlighting, whatever you want) but the only problem is handling those checkboxes. Whenever an item is highlighted and enter is pressed I must catch the event, verify the number of checked items and update dropdown's title.
The methods I found so far are based on using document.createEvent() and fireEvent(), but they both are deprecated (and yes, I can't figgure out how to solve it with CustomEvent).
I've been trying to find an answer for 3 days now, trust me when I say I tried my best.
checkbox.checked = true
checkbox.checked = false
only change checkbox value but won't trigger any event
Since changing a checkbox value doesn't trigger any event, of course it won't trigger neither 'click' nor 'change' event. They must be triggered separately or together on whatever the case, and the listeners must be specific as well, and new Event('change') works just fine. It was a matter of how to trigger and listen the events.
Thanks for the answers :-)
It might sound stupid, but have you tried simply calling click?
checkbox.click()
Not sure if applicable in OP's concrete case (that is not described in the question), but in general it should NOT be necessary to trigger events from inside your own code when it's possible to just call the same function from multiple places, e.g.:
const checkboxes = document.getElementsByTagName('input')
const button = document.getElementById('button')
const postProcess = (msg) => {console.log(`Processing after clicking ${msg}`)}
[...checkboxes].forEach(checkbox => {
checkbox.onclick = (e) => {
postProcess(`checkbox '${e.currentTarget.value}'`)
}
})
button.onclick = () => {
const previous = checkboxes[0].checked
checkboxes[0].checked = !previous
postProcess(`button that turned checkbox 'a' ${previous ? 'off' : 'on'}`)
}
<label><input type="checkbox" value="a">A</label>
<label><input type="checkbox" value="b">B</label>
<button id="button">Toggle A</button>

Javascript changing button and onClick issue

I am trying to use an onClick event in JavaScript and am running into a problem. I want to make a button that changes its id, click handler, and text back and forth when it is clicked - I want it to become a completely different button when clicked the first time, but then revert back to the original button when clicked the second time.
My idea was to write one event handler for the original button being clicked which changes it to the second button and I put this in the function "change()". I also had planned on writing one separate event handler for the new button being clicked which changes it to the original button and I put this in the function "changeBack()".
The problem is that when I click on the original button one time, change() gets called and within it changeBack() automatically gets called exactly when the onClick is defined for the new button and right before the innerHTML is changed. I commented out some of the original lines and put an alert in to illustrate this unwanted behavior. I think somehow the click is still active when the new button gets created, thus forcing it to call changeBack() even though the new button was never clicked. Any help on this would be great. Thank you.
<script type="text/javascript">
function change() {
var x = document.getElementById("button");
x.id = "alternateButton";
x.onClick = changeBack();
x.innerHTML = "Click to Change Me Back";
}
function changeBack() {
var x = document.getElementById("alternateButton");
alert('hi');
//x.id = "button";
//x.onClick = change();
//x.innerHTML = "Click Me";
}
</script>
<button id="button" onClick="change()">Click Me</button>
Events are bound to the elements and not to the ID attribute. Both the handlers are always executed when you click the button.
Also it is a good idea to avoid binding handlers using inline event handlers.
// Find the elemnt
var btn = document.getElementById('button');
// Data attribuet to keep tab of whether it is clicked or not
btn.dataset.clicked = "1";
// Attach event
btn.addEventListener('click', change);
function change() {
var txt = 'Click to Change Me Back';
// Will give you the truthy/falsy value
if(!!this.dataset.clicked) {
this.dataset.clicked = "";
// First implementation
} else {
this.dataset.clicked = "1";
txt = "Click Me";
// The other case
}
this.innerHTML = txt;
}
Check Fiddle
The above comment by Sushanth got me started on the right track by using a truth tester. However, the same problem about the mouse came up - it captures the mouse longer than I want it to (even when using onmousedown). Because of this, right when the new button gets created the old one replaces it, so the new button is never seen. Also, by changing the element's id, I ran into some really strange things such as the program stopping completely if I use an alert - and not continuing after I close the alert, but when I delete the alert, the entire program runs. I guess it's better to leave the ID's alone and only use them as a reference and change the styles dynamically with DOM access rather than the style tag and control other parts of the page using the button by referencing other functions in the switch statement (I'm really new to JavaScript so I'm not sure how else it is done).
Because of these issues but with Sushanth's comment idea, I used two testers: one for which button is currently being shown, and one for the mouse having been pressed or released. I also had some strange issues when putting the code in the header instead of the bottom of the body. Finally, I had to use some custom properties. I hope this helps anybody that wants to use a button that changes its appearance and functionality back and forth as you click on it.
<button id="button1" onmousedown="transformButton1()" onmouseup="release()">Click Me</button>
<p id="one">One</p>
<p id="two">Two</p>
<p id="three">Three</p>
<script type="text/javascript">
var x = document.getElementById("button1");
x["clicked"] = 0;
x["released"] = 1;
function transformButton1() {
var x = document.getElementById("button1");
if (x["released"] == 1) {
switch (x["clicked"]) {
case 0:
x["clicked"] = 1;
x["released"] = 0;
// Other function calls to change other elements on the page, for example:
document.getElementById("two").innerHTML = "I've Changed!!!!!";
x.innerHTML = "Click to Change Me Back";
break;
case 1:
x["clicked"] = 0;
x["released"] = 0;
// Other function calls to change other elements on the page, for example:
document.getElementById("two").innerHTML = "Two";
x.innerHTML = "Click Me";
break;
}
}
}
function release() {
document.getElementById("button1")["released"] = 1;
}
</script>
JSFiddle

Why OnChange Event is not Dispatched When Target Is Manually Set

I'm confused on how JavaScript handles Change Events and am looking for some insight.
Let's say we have two HTML controls; a Checkbox and a Button and I want to use JS to display a message that says how many times the Checkbox has changed from checked to not-checked.
<input type="checkbox" id="cb" />
<button id="btn">Change Checkbox</button>
<div id="msg"></div>
The JS can look something like this:
var count = 0;
var cb = document.getElementById("cb");
var btn = document.getElementById("btn");
var msg = document.getElementById("msg");
cb.addEventListener("change", cb_onChange);
btn.addEventListener("click", btn_onClick);
// Change the state of the Checkbox when user clicks the Button
function btn_onClick() {
cb.checked = !cb.checked;
}
// The state of the Checkbox has changed, so increment the change count and display it
function cb_onChange() {
msg.innerHTML = "Checkbox changed " + count+++" times";
}
Test it out here http://jsfiddle.net/26RWh/
Notice that the OnChange event of the Checkbox is NOT dispatched when the Checkbox is programmatically set at cb.checked = !cb.checked. - i.e. The cb_onChange listener is only executed if/when the user manually clicks the Checkbox.
How come the OnChange event isn't fired when I change the state in code?
This is the way events on input-elements work in javascript.
If you want the callback to be executet you need to manually fire the change-event on the checkbox.
There are questions about this:
do it in pure JavaScript
and with help of jquery
when the browser identifies a change event in checkbox, it sets the checked propery to !checked and calls the subscribed functions which you can assume happens in one function(f1) and which is called when the event occurs. In this case you are not calling the function f1 but just setting the property.

javascript getting a variable from a child to a parent

I shortened my code dramatically but below relays the point pretty efficiently, I'm trying to get the variable "Monitor" to update if the buttons pressed. I can get the variable through to my code if I put all of my code inside of the "button.onclick" function. However, my code won't run until I press the button. I need my code to run and if a button is pressed it updates my code.
<form name="form1">
<span id="buttons">
<input type="button" name="button1" value="funny1"/>
<input type="button" name="button2" value="funny2"/>
</span>
</form>
<script type="text/javascript">
var Monitor, buttonsDiv=document.getElementById("buttons");
Monitor = "funny1"
for (var i=1; i<=2; i++) {
var button = document.form1["button" + i];
button.onclick = function() {
buttons.Monitor = this.value;
};
/*lots of my own code that runs
inside of my for loop waiting
to reference monitor for an update*/
</script>
Hopefully the following code will get you going in the right direction. Instead of wiring up all the events per button, I think you were trying to get it so each button would then call into a function that would set the value of Monitor.
var Monitor = "funny1";
//selecting all elements named button
var buttons = document.querySelectorAll('input[type="button"]');
//For each of the buttons wire up an event listener
for(var i=0, length=buttons.length; i < length;i++)
{
//create a reference shorthand
var button = buttons[i];
//add the event listener for a click
button.addEventListener('click', function(event)
{
//on the event look at the event's target property to find the element that invoked the click
Monitor = event.target.value;
console.log(Monitor); //Output the value of monitor the the console
});
}
This code first finds all the inputs with type=button. I suggest you perhaps give the inputs a class instead to make the selector clearer, your choice. Secondly, I loop through the buttons and wire an event up for each one. The event then sets the value of the Monitor variable.
http://jsfiddle.net/wcf4c/

Categories

Resources