I assembled some code that checks the state of a checkbox and then displays the corresponding message as a string. The default state of the checkbox is "unchecked", but when I reload the page there's no message displaying "Unchecked", it will work as intended once I check the checkbox and uncheck. I want the state to display on page load in a nutshell, not on-change. Here's the code:
<html>
<head>
</head>
<body>
<input type="checkbox" id="checkBox" />
<div id="text"></div>
<script type="text/javascript">
var getId = document.getElementById('text'),
checkbox = document.getElementById('checkBox');
function checkState(){
text.innerHTML = checkbox.checked ? "Checkbox is checked" : "Checkbox is empty";
}
checkbox.onchange = checkState;
</script>
</body>
</html>
You just need to call your own function in addiction to set it as the checkbox onchange event.
Since you're executing the script on the end of the body, it only gets executed when you already have access to the DOM, you just need to call checkState() after it's definition.
<html>
<head>
</head>
<body>
<input type="checkbox" id="checkBox" />
<div id="text"></div>
<script type="text/javascript">
var getId = document.getElementById('text'),
checkbox = document.getElementById('checkBox');
function checkState(){
text.innerHTML = checkbox.checked ? "Checkbox is checked" : "Checkbox is empty";
}
checkbox.onchange = checkState;
checkState();
</script>
</body>
</html>
Right now you're running the function as an onchange handler. That is the event which fires when the state of the checkbox changes, as you have seen. You said:
I want the state to display on page load in a nutshell, not on-change.
Then the fix should be pretty darn obvious: change the checkbox.onchange to a window.onload.
Related
I checked only one checkbox but another click listeners attached to other checkboxes are invoked. I don't think this is a typical case of event bubbling.
How do I solve this issue?
I already checked if this is related to event bubbling. But I don't think so because my input tags are horizontal.
Popup.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h3>Input game title to search metacritic score!</h3><br>
<p>Press the "Enter" key inside the input field to trigger the button.</p>
<input id="gameTitle" value="Example : "Gears 5"">
<input type="checkbox" name="Pc" id="pcCheck">PC<br>
<input type="checkbox" name="Ps4" id="ps4Check">PS4<br>
<input type="checkbox" name="Xbox" id="xboxCheck">XBOX<br>
<input type="checkbox" name="Switch" id="switchCheck">SWITCH<br>
<button id="confirmBtn">Confirm</button>
<p id = "content"></p>
<script src="popup.js"></script>
</body>
</html>
Popup.js
var dict = {};
dict["confirmBtn"] = document.getElementById("confirmBtn");
dict["pcCheck"] = document.getElementById("pcCheck");
dict["ps4Check"] = document.getElementById("ps4Check");
dict["xboxCheck"] = document.getElementById("xboxCheck");
dict["switchCheck"] = document.getElementById("switchCheck");
document.addEventListener('DOMContentLoaded', function() {
dict["confirmBtn"].addEventListener("click", confirmBtnEvent);
dict["pcCheck"].addEventListener("click", CheckEvent("pcCheck"),{capture:true});
dict["ps4Check"].addEventListener("click", CheckEvent("ps4Check"),{capture:true});
dict["xboxCheck"].addEventListener("click", CheckEvent("xboxCheck"),{capture:true});
dict["switchCheck"].addEventListener("click", CheckEvent("switchCheck"),{capture:true});
});
I want one specific event listener to be called when the corresponding checkbox is clicked.
You're not calling addEventListener correctly. The argument should be a function reference, not the result of calling the function. And the options need to be an argument to addEventListener.
dict["pcCheck"].addEventListener("click", function() {
CheckEvent("pcCheck");
},{capture:true});
However, if you change CheckEvent slightly, you can simplify it to:
dict["pcCheck"].addEventListener("click", CheckEvent, {capture:true});
When an event listener is called, this is set to the target of the event, so you can just use this inside the function, rather than calling document.getElementById() with the argument.
I am new to jQuery.
Simply I want to build a password show/hide program.
I have written some code (below), and the first time the program works correctly - the password is showing after clicking on "Show" button. But then the "Hide" feature is not working.
In my code the if part is running each time but the else part never executes. What's wrong here?
$("#btn").click(function() {
if ($("#pass").attr("type", "password")) {
$("#pass").attr("type", "text");
$("#btn").attr("value", "Hide")
} else {
$("#pass").attr("type", "password");
$("#btn").attr("value", "Show")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Password : <input type="password" id="pass">
<input type="button" id="btn" value="Show">
The problem is this line:
if($("#pass").attr("type","password")){
$("#pass").attr("type","password") is setting the value of the "type" attribute, not comparing it to anything. What you need to do is get the value, and then compare it to the value you're checking for:
if($("#pass").attr("type") == "password")) {
Here is a full working example:
N.B. I also added variables to represent the button and textbox, because it's inefficient to repeatedly invoke the jQuery constructor on the same elements.
$(document).ready(function() {
var btn = $("#btn");
btn.click(function() {
var pass = $("#pass");
if (pass.attr("type") == "password") {
pass.attr("type", "text");
btn.attr("value", "Hide")
}
else {
pass.attr("type", "password");
btn.attr("value", "Show")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Password show/hide in Jquery</title>
</head>
<body>
Password : <input type="password" id="pass">
<input type="button" id="btn" value="Show">
</body>
</html>
You may also wish to review the jQuery documentation to help your understanding: http://api.jquery.com/attr/
i want to keep a jquery value for input box value after press enter key or refresh not reload. when click button then set a value of a input box but when page refresh or press enter key then input box value erase. i have uses localStorage but it is not working for me.
here is my html code....
<button id="read">set value</button>
<input type="text" id="value">
here is my jquery.....
$(function(){
$('#read').on('click', function () {
var someVarName = "value";
localStorage.setItem("someVarName", someVarName);
var someVarName = localStorage.getItem("someVarName");
$('#value').val(someVarName)
})
});
Below is the working code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('#read').on('click', function () {
var someVarName = "value";
localStorage.setItem("someVarName", someVarName);
var someVarName = localStorage.getItem("someVarName");
$('#value').val(someVarName)
});
});
</script>
</head>
<body>
<button id="read">set value</button>
<input type="text" id="value">
</body>
</html>
I am trying to implement a small part of my program where when an initial checkbox is clicked, it would open multiple checkboxes are opened up for selection. I don't want to use forloop (or dynamically) to create the multiple checkboxes but I need to manually create them.
My program is below and I am not sure why it doesn't work. If someone can kindly pleaes point me to my mistake, I would greatly appreciate. I am not skilled with PHP/JavaScript.
Thanks!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
<script type="text/javascript">
$(document).ready(function() {
//set initial state.
$('#checkbox').val($(this).is(':unchecked'));
$('#checkbox').change(function() {
if($(this).is(":checked")) {
var box = document.createElement("div");
box.innerHTML = <input type="chkbox" name="checkme"> 2nd checkbox;
document.myForm.appendChild(box);
hasBox = true;
}
});
});
</script>
</head>
<body>
<p>Click on this paragraph.</p>
<form action="">
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>initial checkbox<br>
</body>
</html>
You can also do this with CSS:
.secondary-checkboxes
{
display: none;
}
.primary-checkbox:checked ~ .secondary-checkboxes
{
display: initial;
}
<input type="checkbox" class="primary-checkbox"> Primary checkbox
<br>
<div class="secondary-checkboxes">
<input type="checkbox"> Secondary checkbox 1
<br>
<input type="checkbox"> Secondary checkbox 2
<br>
<input type="checkbox"> Secondary checkbox 3
<br>
</div>
Source: this Stack Overflow question
Your on the right track.
You have a few problems in your code.
1) You forgot to enclose your new checkbox tag within quotation marks.
box.innerHTML = <input type="chkbox" name="checkme"> 2nd checkbox;
should be:
box.innerHTML = "<input type=\"checkbox\" name=\"checkme\"> 2nd checkbox<br>";
Also note the change from type "chkbox" to "checkbox"
2) To set the initial state for a checkbox I would use the inbuilt prop function in JQuery. For example:
$('#checkbox').prop('checked', false);
rather than your code of:
$('#checkbox').val($(this).is(':unchecked'));
3) The last problem is when you append the new checkbox to the form. The way that i would do this is using JQuery again:
$("#myForm").append(box);
and give the form element an id of "myForm"
Please find below my full code which works to your requirements:
$(document).ready(function() {
//set initial state.
$('#checkbox').prop('checked', false);
$('#checkbox').on('click', function() {
if($(this).is(":checked")) {
var box = document.createElement("div");
box.innerHTML = "<input type=\"checkbox\" name=\"checkme\"> 2nd checkbox<br>";
$("#myForm").append(box);
hasBox = true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<p>Click on this paragraph.</p>
<form action="" id="myForm">
<input id="checkbox" name="click" type="checkbox"/>initial checkbox<br>
</form>
Hope that you found this useful.
I want to make a submit button that only activates when a radio button is checked, it works perfectly in JS fiddle http://jsfiddle.net/sYNj7/94/
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
but it doesn't work when I try to make it into a html page with notepad++. I get the radio button next to a disabled submit button but the submit button doesn't activate when the radio button is checked. this is the code I have at the moment.https://gist.github.com/anonymous/e5f19f5745396926ce02
Currently you attempt to access HTML elements before the page is fully loaded; they are not available at that point.
1. Put your code in a named function
function myFunc() {
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
....
2. Use the body onload event to ensure it runs when all the HTML elements are available for use:
<body onload="myFunc();">
(JSFiddle does this for you by default)
Just put your script just before closing body tag:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Captive portal</title>
</head>
<body>
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
<script>
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
</script>
</body>
</html>
It happens because you're trying to get the elements before they are rendered in the page.
In jsFiddle, it works, because they wrap your code into a onload event, and then, all the elements are already rendered when you try to use them.
There are two simpler ways of achieving what you want:
You can put your script tag right before ending the body tag, e.g:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!-- all your content -->
<script>
</script>
</body>
</html>
Or you can wrap your code in a onload or DOMContentLoaded event:
<script>
document.addEventListener('DOMContentLoaded', function(e) {
// your code goes here
});
</script>