(Vanilla) JS: Checkbox "checked" returning unexpected results - javascript

Using the pen below you can see there are two elements, a button and a checkbox input.
When the button is clicked I would like to determine the status of checkbox (clicked/not-clicked).
Regardless of the visual check mark presence or not, the console always logs false. Why is this?
https://codepen.io/sterlingbutters/pen/ZEGGgvm
EDIT (code):
HTML:
<input id='stall' type="checkbox">
<button id='button'>Test
JS:
var stall = document.getElementById('stall').checked;
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall);
}

You have to reasign stall on button click.
So Using
button.onclick = function () {
var stall = document.getElementById('stall').checked
console.log(stall);
}
It works fine.

Try this instead: assign the element to the variable, and then inside your onclick function you get the checked property every time it runs.
If you just store the boolean value of checked in a variable, it will never update. Primitive types like booleans are always stored as simple values, not as auto-updating references back to the original property.
var stall = document.getElementById('stall');
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall.checked);
}
<input id='stall' type="checkbox">
<button id='button'>Test

Once you assigned "stall", it won't be re-assiged in "button.onclick". You must re-assign, such as
var button = document.getElementById('button');
button.onclick = function () {
var stall = document.getElementById('stall').checked;
console.log(stall);
}
or better
var stall = document.getElementById('stall');
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall.checked);
}

Related

javascript onclick set to false

document.getElementById("btn2").onclick = false;
I did this to stop getting on click event after the first one and when I want to set it back to normal
document.getElementById("btn2").onclick = True;
it does not take click events
You could always disable the button, like this:
document.getElementById("btn2").disabled = true;
This sets the disabled attribute to true, therefore stopping the onClick function from being called when the user clicks the button.
Declare a variable boolean and change using logical not operator (!: see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT), example:
let toggle = true;
let button = document.querySelector('button');
let result = document.querySelector('span');
button.onclick = () => {
toggle = !toggle;
result.textContent = `Your switch to ${toggle}`;
}
<button>Click me</button>
<span></span>
You may not set onclick event as True instead try this way.
const setEvent = (enable) => {
if(enable){
document.getElementById("btn2").addEventListener('click', onClickEvent);
}
else{
document.getElementById("btn2").removeEventListener('click');
}
}
function onClickEvent(){
//Your actual event when clicking the button
}
//Now enable or disable the event as follows
setEvent(true); //Will attach the event
setEvent(false); //Will remove the event
Make sure you call setEvent(true) once only, because it can attach multiple events.

Facing problem in JavaScript function execution

I am trying to make a simple Shopping List App in which user can Add, Delete and mark the task done when completed. So far, I am able to add the task but facing problem in executing the done and delete functions. I am getting an error because when I execute it, the done and delete buttons are not there but what should I do to fix it?
var inp = document.getElementById("form");
var button = document.getElementById("click");
//Create List Function with Done and Delete Buttons
function addVal() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var span = document.createElement("span");
var done = document.createElement("button");
var del = document.createElement("button");
li.appendChild(document.createTextNode(""));
span.appendChild(document.createTextNode(inp.value));
done.appendChild(document.createTextNode("Done"));
del.appendChild(document.createTextNode("Delete"));
li.appendChild(span);
li.appendChild(done);
li.appendChild(del);
done.setAttribute("class", "doneBut");
del.setAttribute("class", "delBut");
ul.appendChild(li);
inp.value = "";
}
//Get Input Length
function checkLength() {
return inp.value.length;
}
//Run function on Button Click
function onButtonClick() {
if (checkLength() > 0) {
addVal();
}
}
//Run function on Enter Keypress
function onEnter(event) {
if (checkLength() > 0 && event.which === 13) {
addVal();
}
}
//Trigger Events
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
//Done and Delete Button Functions
var doneButton = document.getElementsByClassName("doneBut");
var deleteButton = document.getElementsByClassName("delBut");
function doneTask() {
doneButton.parentNode.classList.add("done");
}
function delTask() {
deleteButton.parentNode.classList.add("delete");
}
doneButton.addEventListener("click", doneTask);
deleteButton.addEventListener("click", delTask);
<input type="text" placeholder="Enter Your Task..." id="form" />
<button id="click">Add Task</button>
<h2>List:</h2>
<ul id="list"></ul>
Please Help.
Your problem is that the code tries to add events before the buttons exist. The buttons don’t exist until the addVal function gets called. Since addVal is not being called before the you try to add your event handlers, the getElementById returns null, and you attempt to add an event listener to null.
Additionally it looks like you’re planning to add multiple done and delete buttons. That wouldn’t normally be a problem, except you’re referencing them by ID, and IDs MUST be unique. You’ll need to switch this to a class or an attribute, since you’ll need one per item in the shopping cart.
You’ll probably want to look into event delegation, so that you can add your events once to the page before any buttons exist. https://javascript.info/event-delegation
It's most likely because your script is running before your code is running. Add the <script> tags just before the closing </body> tag to fix it:
<script>/* Your code here */</script>
</body>
You need to place this in a window.onload function, or run it in a function inside of the body tag's onload. Those elements don't exist yet when the script is run:
window.onload = function() {
var inp = document.getElementById("form");
var button = document.getElementById("click");
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
}

Event listeners/onclick events for buttons created in javascript function

I have a javascript button (button A), when it is clicked, it generates some new elements, including another button (button B). I would like a way to listen on button B, and then execute a separate function.
I tried editing Button B's 'onclick' attribute in javascript. This did not work.
HTML:
<input id="addTaskButton" type="submit" value="add task" onclick="addTaskFunction()"></input>
Javascript:
function buttonB()
{
// Not working
}
function addTaskFunction()
{
var doneButton = document.createElement("BUTTON");
doneButton.id = "doneButton";
doneButton.innerHTML = "DONE";
doneButton.onclick = "buttonB()";
}
i am expecting the listener to perform buttonB when ran. Instead, i get no response.
Correct use is as follows
function addTaskFunction()
{
var doneButton = document.createElement("BUTTON");
doneButton.id = "doneButton";
doneButton.innerHTML = "DONE";
doneButton.onclick = buttonB;
}
This works for me:
doneButton.onclick = function(){buttonB()};

Register an event for changing html input value in javascript

Is it possible to register an event for changing html input value in javascript?
I mean I have an input. And when I type into it an event is registered, but when I update its (inputs) value through javascript the input event is not called. What is a workaround here?
For example, when you type into input the resulting text is updated, but when you clear the input using button (in other words through javascript) the input event is not registered.
html
<input id="inpt" oninput="updateText()" />
<div id="txtDiv">
resulting text
</div>
<button id="btn">
Click
</button>
js
const input = document.getElementById("inpt");
input.addEventListener('input', function() {
const resultingText = document.getElementById("txtDiv");
resultingText.innerHTML = input.value;
alet("called");
});
const btn = document.getElementById("btn");
btn.addEventListener('click', function() {
input.value = "";
});
fiddle.
I found out that if you separate the logic in the event listener into its own function, you could just call that function when the button is pressed.
const input = document.getElementById("inpt");
input.addEventListener('input', function() {
changeText();
});
const btn = document.getElementById("btn");
btn.addEventListener('click', function() {
input.value = "";
changeText();
});
function changeText() {
const resultingText = document.getElementById("txtDiv");
resultingText.innerHTML = input.value;
alert("called");
}
JS Fiddle: https://jsfiddle.net/joabysvt/1/

How to tell if a button is clicked

I have this code:
<script type="text/javascript">
function changestate()
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(document.getElementById("Play").onclick == true)
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick="changestate();"/>
I'm trying to know when the button is clicked, and have that if button is clicked in the if statement. I want to know this so I can change the value that is inside the text box. The problem is, I do not know how to tell when the button is clicked. If you could help me out that would be great.
The onclick attribute identifies what should happen when the user clicks this particular element. In your case, you're asking that a function be ran; when the function runs, you can rest assured that the button was clicked - that is after all how the function itself got put into motion (unless you invoked it some other way).
Your code is a bit confusing, but suppose you had two buttons and you wanted to know which one was clicked, informing the user via the stateTextBox value:
(function () {
// Enables stricter rules for JavaScript
"use strict";
// Reference two buttons, and a textbox
var playButton = document.getElementById("play"),
stateTextBox = document.getElementById("state"),
ignoreButton = document.getElementById("ignore");
// Function that changes the value of our stateTextBox
function changeState(event) {
stateTextBox.value = event.target.id + " was clicked";
}
// Event handlers for when we click on a button
playButton.addEventListener("click", changeState, false);
ignoreButton.addEventListener("click", changeState, false);
}());
You can test this code live at http://jsfiddle.net/Y53LA/.
Note how we add event-listeners on our playButton and ignoreButton. This permits us to keep our HTML clean (no need for an onclick attribute). Both of these will fire off the changeState function anytime the user clicks on them.
Within the changeState function we have access to an event object. This gives us some details about the particular event that took place (in this case, the click event). Part of this object is the target, which is the element that was clicked. We can grab the id property from that element, and place it into the value of the stateTextBox.
Here is the adjusted HTML:
<input type="button" value="Play with Pogo" id="play" />
<input type="text" id="state" />
<input type="button" value="Ignore with Pogo" id="ignore" />​
You can know if button clicked by using a flag (true or false).
var flag = false;
window.addEventListener("load", changestate, false);
function changestate() {
var StateTextBox = document.getElementById("State");
var PlayButton = document.getElementById("Play");
PlayButton.addEventListener("click", function () {
flag = true;
})
PlayButton.addEventListener("click", change)
function change() {
if (flag) {
StateTextBox.value = "Happy";
}
}
}
Looking back on this, many years later, you could simply do:
<script type="text/javascript">
function changestate(action)
{
var StateTextBox = document.getElementById("State");
var IgnoreTextBox = document.getElementById("Ignore");
var PlayButton = document.getElementById("Play");
if(action == "Play")
{
StateTextBox.value = "Happy";
}
}
</script>
<input TYPE="button" VALUE="Play with Pogo" id="Play" onClick='changestate("Play");'/>

Categories