I'm trying to build a dynamic "reset" button which changes its innerText twice, in a loop: once when first clicked (changing from "Reset" to "Are you sure?") and once when clicked again (changing from "Are you sure?" to "Reset"). However, I can't get to modify the innerText inside the callback. It seems like I can modify the innerText just fine from the DOM console, so I assume that there's something that I don't know yet in terms of how event callbacks work in JS, and I can't figure out what it is.
function show_confirm_button() {
document.getElementById('reset-button').innerText = "Are you sure?";
document.getElementById('reset-button').onclick = reset_button;
}
function reset_button() {
/* resetting things here */
document.getElementById('reset-button').innerText = "Reset";
document.getElementById('reset-button').onclick = show_confirm_button;
}
show_confirm_button() is used in a simple bootstrap button:
<button class="..." type="button" onclick=show_confirm_button()>
<span id="reset-button">Reset</span>
</button>
What am I missing?
As #Barmar said:
You should be changing the onclick of the button, NOT the span.
This should work:
function show_confirm_button() {
document.getElementById('reset-button-text').innerText = "Are you sure?";
document.getElementById('reset-button').onclick = reset_button;
}
function reset_button() {
/* resetting things here */
document.getElementById('reset-button-text').innerText = "Reset";
document.getElementById('reset-button').onclick = show_confirm_button;
}
<button class="..." type="button" onclick=show_confirm_button() id="reset-button">
<span id="reset-button-text">Reset</span>
</button>
Related
<body>
<button onclick="yesClick()">Click me for a suprise word!</button>
<script>
function yesClick() {
alert("Are you sure?")
alert("Check again... but first click ok")
let element = document.createElement("div");
element.innerText = clickMe;
let clickMe = "Gigachad"
// Loop
while (true) {
document.body.appendChild(element)
}
}
</script>
</body>
Click on the button, two alerts pop up saying "Are you sure?" and "Check again... but first click ok"). When clicked, the while loop should run infinitely since it's a while true loop, right? Well not for me... When clicked a new div should be added with a text inside stating "Gigachad" (don't judge it's just practice) but it doesn't work.
I reviewed the code, had my group partner check it out but didn't work
Your while loop will run forever because true will always be true and there's nothing in the loop that will change that. In fact, the loop is not even necessary and is probably causing the browser to lock up.
Also, your let statements must precede your use of the let variables.
<button onclick="yesClick()">Click me for a suprise word!</button>
<script>
function yesClick() {
alert("Are you sure?")
alert("Check again... but first click ok")
let element = document.createElement("div");
let clickMe = "Gigachad"
element.innerText = clickMe;
document.body.appendChild(element)
}
</script>
Now, you also really shouldn't be using inline event attributes to set up event handlers as that is a 25+ year old legacy way to work with events. And, instead of an alert when you are asking a question, use a confirm.
<button type="button">Click me for a suprise word!</button>
<script>
document.querySelector("button").addEventListener("click", function() {
if(confirm("Are you sure?")) {
alert("Check again... but first click ok")
let element = document.createElement("div");
element.textContent = "Gigachad";
document.body.appendChild(element);
}
});
</script>
I have a button. The button works fine. After I have pressed the button, then it shall not be possible to press the button again. It will be best if the button looks diabled.
I have already tried with document.getElementById("id").disabled = true; but I can't make this work.
PHP code for the button. The code makes a list of buttons. Each button has id= 1, 2, 3 etc.
if($_COOKIE["sorterdb"]=='GR' || empty($_COOKIE["sorterdb"])){$dblinjer[$i]['nrlink']='<span id="para'.$i.'"></span><div class="s-12 l-12"><button type="button" id="'.$i.'" value="'.$dblinjer[$i]['loebid'].'_'.$dblinjer[$i]['tid'].'_'.$dblinjer[$i]['utcstart'].'" onclick=baadimaal("baadimaal",this)>'.$dblinjer[$i]['buttonnrsejl'].'</button></div>';}
javascript:
function baadimaal(str,el) {
var x = el.value
var id = el.getAttribute("id")
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("container"+id).innerHTML = this.responseText; //her placeres svaret, som kommer tilbage fra hide-ajax-svar filen
}
xhttp.open("GET", "hide-ajax-svar.php?funk=" + str + "¶=" + x + "&i=" + id); //overfør str og x til hide-ajax-svar filen
xhttp.send();
}
You can set the button's disabled property to false (see Sütemény András's answer), but that may not work in all browsers. You can also remove the listener, however that doesn't make the button look disabled.
So a belt and braces approach is to do both, e.g.
window.onload = function() {
// Listener
function clickFn() {
console.log('I\'ve been clicked! But no more…');
// Make button appear disabled
this.disabled = true;
// Remove the listener
this.removeEventListener('click', clickFn);
}
// Add the listener to the button
document.getElementById('b0').addEventListener('click', clickFn, false);
};
<button id="b0">Click me</button>
Note that if using setAttribute as in:
button.setAttribute('disabled', true);
the second argument is required but its value is irrelevant (it can be false, 'foo bar', 42, whatever). Regardless of the value, the element will be disabled, which is a hangover from ancient times when boolean attributes were added to HTML. Their presence alone does the job, they don't take a value (e.g. <button disabled>foo</button> creates a disabled button).
To unset the attribute (i.e. to enable the button again), use removeAttribute.
If you have a button like this:
<button class="button" id="1">Button 1</button>
<button class="button" id="2">Button 2</button>
<button class="button" id="3">Button 3</button>
You can add javascript eventlistener, do the job, than disable:
const buttons = document.querySelectorAll(".button")
buttons.forEach((item) => {
item.addEventListener("click", ()=>{
// DO SOMETHING WHITH YOUR BUTTON
console.log(`You've clicked on ${item.id} and now I'm gonna disable it.`)
// disable
item.disabled = true;
})
})
And depending on your code, maybe you should add "removeEventListener" on your button.
I want my button to trigger a download of a PDF file when clicked. However, I am having trouble getting the button to fire the function when clicked. For now, I am just wanting the button to console.log "it works"
I have selected the correct element, and defined the type as "button", and am able to console.log the button. But when attaching the button.onclick()= function{ console.log("it works");}; it does not trigger the console.log in the console. I have also put the onclick function into a window.onload function.
<div id="resume" class="resume">
<button type="button" id="resume-button" class="resume-button">RESUME</button>
</div>
--JavaScript--
var button = document.querySelectorAll('.resume-button');
window.onload = function(){
button.onclick = function(){
console.log("yay its working");
}; }
I am expecting the console to output "it works" when the button is clicked, but nothing happens when clicked.
document.querySelectorAll returns an NodeList so that you need to access the button as the first element of this NodeList (document.querySelectorAll('.resume-button')[0])
var button = document.querySelectorAll('.resume-button')[0];
button.onclick = function(){
console.log("yay its working");
};
<div id="resume" class="resume">
<button type="button" id="resume-button" class="resume-button">RESUME</button>
</div>
Also note there is no need to wrap the onclick function assignment into window.onload
I am new to Javascript, and i run into some big problems. I got some functions, which I can type into a text field and press enter, and the functions works. But i have created 4 buttons, which i want to connect to the actions.. i got 4 actions: "UP","DOWN","LEFT" and "RIGHT".
This is the js fiddle over my code: http://jsfiddle.net/n24gQ/
I have made the buttons like this but I dont know what to write inside the OnClick tag?
<div id="gamebuttons">
<button id="up" button onClick="">UP</button>
<button id="down" button onClick="">DOWN</button>
<button id="left" button onClick="">LEFT</button>
<button id="right" button onClick="">RIGHT</button>
</div>
I hope you can understand what my problem is. I made 4 javascript cases which I want to bind to 4 html buttons if possible.. :) It is the cases: "frem" "tilbage" "hoejre" and "venstre" i need to bind.. Sorry not everything in the code is english, but it should be understandable..
Fiddle
You can simply write the function name you've defined for the buttons into the onclick attribute, e.g. like this:
<button id="up" type="button" onclick="alert('UP'); return false;">UP</button>
However, as your buttons already have id's you can also check if one of those id's got clicked without the need of onclick in your markup:
JavaScript:
var buttonUp = document.getElementById('up');
buttonUp.onclick = function() { myFunction(); return false; }
jQuery:
$('#up').on('click', myFunction());
Instead of using inline handlers (bad practice) or multiple handlers for each button, I would use event delegation on your button wrapper, like so
$('#gamebuttons').on('click', 'button', function() {
/* get the id attribute of the clicked button */
var button_id = this.id;
case (button_id) {
"UP" : /* code for up button */ break;
"DOWN" : /* code for down button */ break;
"LEFT" : /* code for left button */ break;
"RIGHT" : /* code for right button */ break;
}
});
Please pass the function name inside the OnClick tag
for example if you want to associate playGame function to DOWN button
write
<button id="down" onclick="playGame();">DOWN</button>
I think these below changes will give you solution.
Instead of the first button, you need to bind events to all of the buttons which you required. Currently, querySelector() getting only first button to bind events. So, use querySelectorAll()
Replace this code
var button = document.querySelector("button");
button.style.cursor = "pointer";
button.addEventListener("click", clickHandler, false);
button.addEventListener("mousedown", mousedownHandler, false);
button.addEventListener("mouseout", mouseoutHandler, false);
With below code
var gamebuttonslist=document.querySelectorAll("#gamebuttons button");
for (var vitem=0;vitem<gamebuttonslist.length;vitem++) {
if (typeof gamebuttonslist[vitem] != "undefined" && gamebuttonslist[vitem] != null) {
gamebuttonslist[vitem].style.cursor = "pointer";
gamebuttonslist[vitem].addEventListener("click", clickHandler, false);
gamebuttonslist[vitem].addEventListener("mousedown", mousedownHandler, false);
gamebuttonslist[vitem].addEventListener("mouseout", mouseoutHandler, false);
}
}
I have a button:
<button id="a" onclick="Foo()">Button A</button>
When I click this button the first time, I want it to execute Foo (which it does correctly):
function Foo() {
document.getElementById("a").onclick = Bar();
}
What I want to happen when I click the button the first time is to change the onclick function from Foo() to Bar(). Thus far, I've only been able to achieve an infinite loop or no change at all. Bar() would look something like this:
function Bar() {
document.getElementById("a").onclick = Foo();
}
Thus, clicking this button is just alternating which function gets called. How can I get this to work? Alternatively, what's a better way to show/hide the full text of a post? It originally starts shorted, and I provide a button to "see the full text." But when I click that button I want users to be able to click the button again to have the long version of the text go away.
Here's the full code, if it helps:
function ShowError(id) {
document.getElementById(id).className = document.getElementById(id).className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Text").className = document.getElementById(id+"Text").className.replace(/\bheight_limited\b/, '');
document.getElementById(id+"Button").innerHTML = "HIDE FULL ERROR";
document.getElementById(id+"Button").onclick = HideError(id);
}
function HideError(id) {
document.getElementById(id).className += " height_limited";
document.getElementById(id+"Text").className += " height_limited";
document.getElementById(id+"Button").innerHTML = "SHOW FULL ERROR";
document.getElementById(id+"Button").onclick = "ShowError(id)";
}
Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.
document.getElementById("a").onclick = Bar;
Looking at your other code you probably want to do something like this:
document.getElementById(id+"Button").onclick = function() { HideError(id); }
var Foo = function(){
document.getElementById( "a" ).setAttribute( "onClick", "javascript: Boo();" );
}
var Boo = function(){
alert("test");
}
Do not invoke the method when assigning the new onclick handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).
document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );
I recommend this approach:
Instead of having two click handlers, have only one function with a if-else statement. Let the state of the BUTTON element determine which branch of the if-else statement gets executed:
HTML:
<button id="a" onclick="toggleError(this)">Button A</button>
JavaScript:
function toggleError(button) {
if ( button.className === 'visible' ) {
// HIDE ERROR
button.className = '';
} else {
// SHOW ERROR
button.className = 'visible';
}
}
Live demo: http://jsfiddle.net/simevidas/hPQP9/
You could try changing the button attribute like this:
element.setAttribute( "onClick", "javascript: Boo();" );
What might be easier, is to have two buttons and show/hide them in your functions. (ie. display:none|block;) Each button could then have it's own onclick with whatever code you need.
So, at first button1 would be display:block and button2 would be display:none. Then when you click button1 it would switch button2 to be display:block and button1 to be display:none.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info
submitting a GET form with query string params and hidden params disappear