I have this page that has multiple checkboxes and when clicked, an element appears.
I have this stripped down version to show it simply:
<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
Checkbox 1: <input type="checkbox" id="check1" onclick="box1()"><br>
Checkbox 2: <input type="checkbox" id="check2" onclick="box2()">
<p id="fill">No boxes are checked</p>
<p id="text" style="display:none">Checkbox1 is CHECKED!</p>
<p id="text2" style="display:none">Checkbox2 is CHECKED!</p>
<script>
function box1() {
var checkBox = document.getElementById("check1");
var text = document.getElementById("text");
var fill = document.getElementById("fill");
if (checkBox.checked == true){
text.style.display = "block";
fill.style.display = "none";
} else {
text.style.display = "none";
fill.style.display = "block";
}
}
</script>
<script>
function box2() {
var checkBox = document.getElementById("check2");
var text = document.getElementById("text2");
var fill = document.getElementById("fill");
if (checkBox.checked == true){
text.style.display = "block";
fill.style.display = "none";
} else {
text.style.display = "none";
fill.style.display = "block";
}
}
</script>
</body>
</html>
My problem is that the text shows even a box is checked as shown in the image. How can I do this effectively? thanks!
I'd add the same listener to both checkboxes, and have that listener check the state of both. Then, if both are not checked, display the fill:
const isCheckeds = document.querySelectorAll('.is-checked');
const fill = document.querySelector('#fill');
function validate() {
let anyChecked = false;
document.querySelectorAll('input').forEach((checkbox, i) => {
if (checkbox.checked) {
anyChecked = true;
}
isCheckeds[i].style.display = checkbox.checked ? 'block' : 'none';
});
fill.style.display = anyChecked ? 'none' : 'block';
}
<p>Display some text when the checkbox is checked:</p>
Checkbox 1: <input type="checkbox" onclick="validate()"><br>
Checkbox 2: <input type="checkbox" onclick="validate()">
<p id="fill">No boxes are checked</p>
<p class="is-checked" style="display:none">Checkbox1 is CHECKED!</p>
<p class="is-checked" style="display:none">Checkbox2 is CHECKED!</p>
Note that inline handlers should be avoided. Strongly consider attaching them properly with Javascript instead. You could also consider using a change listener instead of a click listener (for better accessablity), and you could surround the inputs in a <label> to make them more clickable:
const isCheckeds = document.querySelectorAll('.is-checked');
const fill = document.querySelector('#fill');
const checkboxes = document.querySelectorAll('input');
function validate() {
let anyChecked = false;
checkboxes.forEach((checkbox, i) => {
if (checkbox.checked) {
anyChecked = true;
}
isCheckeds[i].style.display = checkbox.checked ? 'block' : 'none';
});
fill.style.display = anyChecked ? 'none' : 'block';
}
for (const checkbox of checkboxes) {
checkbox.addEventListener('change', validate);
}
<p>Display some text when the checkbox is checked:</p>
<label>Checkbox 1: <input type="checkbox"></label><br>
<label>Checkbox 2: <input type="checkbox"></label>
<p id="fill">No boxes are checked</p>
<p class="is-checked" style="display:none">Checkbox1 is CHECKED!</p>
<p class="is-checked" style="display:none">Checkbox2 is CHECKED!</p>
You forgot to define fill through a document.getElementById in the second checkbox. Right now you are disabling the fill on the first checkbox when interacting with the second one. I think this is causing some problems.
Javascript is not necessary for this task: with your markup structure you could use CSS only
:checked ~ p, #cb1, #cb2 {
display: none;
}
#check1:checked ~ #cb1,
#check2:checked ~ #cb2 { display: block; }
<p>Display some text when the checkbox is checked:</p>
Checkbox 1: <input type="checkbox" id="check1"><br>
Checkbox 2: <input type="checkbox" id="check2">
<p id="cb0">No boxes are checked</p>
<p id="cb1">Checkbox1 is checked</p>
<p id="cb2">Checkbox2 is checked!</p>
Related
I want to add a custom REQUIRED checkbox at the checkout page in my opencart 2.1.0.1 version (using journal theme).
I will create it easily with this <input type="checkbox"
but how can i use javascript to make it required?
Simply check for the checked attribute of your checkbox. According to that, submit your form or prevent it from submitting.
function validate() {
var checkbox = document.querySelector('#check');
if (!checkbox.checked) {
alert("Please check the checkbox!");
return false;
}
return true;
}
<form onsubmit="return validate()" action="">
<input type="checkbox" id="check">
<button>Send</button>
</form>
Edit:
If you don't have a form in your HTML, you could disable the submit button until the checkbox is checked like this:
function enableSubmit() {
var button = document.querySelector('#btn');
var checkbox = document.querySelector('#check');
if (checkbox.checked == false) {
button.setAttribute('disabled', '');
} else if (checkbox.checked == true) {
button.removeAttribute('disabled');
}
}
<input type="checkbox" id="check" onclick="enableSubmit()"><button type="submit" id="btn" disabled>Submit</button>
Edit 2
If you want to display an error message only, toggling the visibility of a div would be an option:
function validate() {
var checkbox = document.querySelector('#check');
var errorDiv = document.querySelector('#error');
if (checkbox.checked == false) {
errorDiv.style.display = "block";
} else if (checkbox.checked == true) {
errorDiv.style.display = "none";
}
}
#error {
width: 100%;
height: 20px;
background-color: #f44b42;
}
<input type="checkbox" onclick="validate()" id="check"><button id="btn">Send</button>
<div id="error" style="display: block">Please check the checkbox.</div>
I would like to alert the amount of check boxes that are checked in a specific div (not the ones in the <head>!), here is the code :
HTML
<div class="changer">
<label><input id="mode" type="checkbox" name="mode" value="Mode" onclick="mode()" />Mode</label><br />
<label><input id="map" type="checkbox" name="map" value="Map" onclick="map()"/>Map</label><br />
<label><input id="joueurs" type="checkbox" name="joueurs" value="Joueurs" onclick="joueurs()" />Joueurs</label><br />
<label><input id="points" type="checkbox" name="points" value="Points" onclick="points()" />Points</label><br />
</div>
</head>
<body>
<div id="text">
</div>
</body>
<button id="send" onclick="send()">Envoyer</button>
Javascript
function joueurs() {
if((document.getElementById("joueurs").checked == true)) {
joueursall.style.display = 'inline';
text.style.display = 'inline';
}
else {
if((document.getElementById("mode").checked == true)) {
modeall.style.display = 'none';
document.getElementById('mode').checked = false;
}
joueursall.style.display = 'none';
text.style.display = 'none';
}
}
document.getElementById("playerlist").addEventListener("change", function() {
var selected = this.value;
document.getElementById("text").innerHTML = "";
var html = '';
for (var i = 0; i < selected; i++) {
html += '<div class="grpjoueur"> <span class="sub-text">Player</span> <label><input type="checkbox" name="botbot" value="BOT"/>BOT</label </div>';
}
document.getElementById("text").innerHTML = html;
});
Here is the Javascript, it adds 'Joueurs' Dropdownlist if Joueurs is checked and then pop X times something, including a check box, according to the number selected in the Dropdownlist in the #text div
I tried multiple things but always return 0 or all the checkboxes...
In vanilla JS you can use querySelectorAll to query the checkboxes, and then .length to get the number of checkboxes.
var checkboxes = document.querySelectorAll("input[type='checkbox']");
alert(checkboxes.length);
CodePen Demo
If you want to alert only the length of the checked checkboxes, you can query them like this:
var checkedInputs = document.querySelectorAll("input:checked");
alert(checkedInputs.length);
CodePen Demo
when you click on the button, it will alert the number of checked boxes
I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine. What I would like to do is have the checkboxes perform their functions when select all is clicked. It works at the moment, but only when I refresh the page. I would like it to happen when select all is clicked.
Here's what I've been playing with so far:
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
this.click();
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 1
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 2
</label>
<label class="js-label">
<input type="checkbox" class="js-checkbox"/>
Checkbox 3
</label>
<button type="button" class="js-button">Check/uncheck all</button>
<div class="js-result"></div>
JSFiddle
CheckBox should be handled with onchange event.
Below code I am firing an event whenever the checkbox checked programmatically.
Below code may help you
function setAllCheckboxes(divId, sourceCheckbox) {
divElement = document.getElementById(divId);
inputElements = divElement.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++)
$('.checkbox').each(function() {
this.checked = true;
/* this.click(); */
this.fireevent('onChange');
/* or you can call this.onChange(); */
});
{
if (inputElements[i].type != 'checkbox')
continue;
inputElements[i].checked = sourceCheckbox.checked;
}
}
In case you are using only java script.
Below is the very simple running example. which consumes short time without any use of external library as JQuery
HTML code
<html>
<head>
<title>test</title>
<script>
function amend(a)
{
document.getElementById("ta").value += a;
}
function checkAll()
{
var textboxes = document.getElementsByClassName("cb");
for(i=0;i<textboxes.length;i++)
{
textboxes[i].checked=true;
textboxes[i].onchange();
}
}
</script>
</head>
<body>
<textarea rows="4" cols="50" id="ta">
Below the outputs
</textarea>
<div id="checkdiv">
<input type="checkbox" onChange="amend(this.value)" value="data to add 1" class="cb">First</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 2" class="cb">Second</input>
<br>
<input type="checkbox" onChange="amend(this.value)" value="data to add 3" class="cb">Third</input>
<br>
<input type="checkbox" onChange="checkAll()">Check all</input>
</div>
</body>
</html>
I have two radio buttons: Click the first radio button and a three textboxes appear if they start entering information and then change their mind and select the second radio button it does not clear the text they have entered. So what I am trying to figure out is if there is a way make it clear the text from those textboxes when a new radio button (of the same group) is chosen. Any help is greatly appreciated!
http://jsfiddle.net/k0paz2pj/
<input
type="radio"
value="Yes"
name="lien"
id="lien"
onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input
type="radio"
value="None"
name="lien"
id="nolien"
onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<div id="div1" style="display:none">
<div class="clearfix">
<p>
<label for="lname">Lienholder Name:</label>
<input
type="text"
name="lienlname"
id="lienlname">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input
type="text"
name="lienladdress"
id="lienladdress">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input
type="text"
name="lienldate"
id="datepicker2">
</p>
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<br>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
}
}
</script>
One approach, staying with the plain JavaScript from your question/JS Fiddle demo:
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
} else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
// getting all the input elements within '#div1' (using a CSS selector):
var inputs = document.querySelectorAll('#div1 input');
// iterating over those elements, using Array.prototype.forEach,
// and setting the value to '' (clearing them):
[].forEach.call(inputs, function (input) {
input.value = '';
});
}
}
JS Fiddle demo.
A marginally more concise form of the above (or, if not more concise, with less repetition):
function showhideForm(lien) {
var isYes = lien.trim().toLowerCase() === 'yes',
div1 = document.getElementById('div1'),
div2 = document.getElementById('div2');
div1.style.display = isYes ? 'block' : 'none';
div2.style.display = isYes ? 'none' : 'block';
if (!isYes) {
[].forEach.call(div1.getElementsByTagName('input'), function (input) {
input.value = '';
});
}
}
JS Fiddle demo.
And, finally, a version that moves away from the obtrusive JavaScript of in-line event-handling (onclick, onchange, etc):
function showhideForm() {
// 'this' in the function is the radio-element to which
// the function is bound as an event-handler:
var isYes = this.value.trim().toLowerCase() === 'yes',
div1 = document.getElementById('div1'),
div2 = document.getElementById('div2');
div1.style.display = isYes ? 'block' : 'none';
div2.style.display = isYes ? 'none' : 'block';
if (!isYes) {
[].forEach.call(div1.getElementsByTagName('input'), function (input) {
input.value = '';
});
}
}
// finding the elements with the name of 'lien':
var lienRadios = document.getElementsByName('lien');
// iterating over those elements, using forEach (again):
[].forEach.call(lienRadios, function (lien) {
// adding a listener for the 'change' event, when it
// occurs the showhideForm function is called:
lien.addEventListener('change', showhideForm);
});
JS Fiddle demo.
References:
Array.prototype.forEach().
document.getElementsByTagName().
document.getElementsByName().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().
String.prototype.toLowerCase().
String.prototype.trim().
You can always use this when another radio is checked:
$("#div1 .clearfix input:text").val("");
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 .clearfix input:text").val("");//here use to clear inputs
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<div id="div1" style="display:none">
<div class="clearfix">
<p>
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" id="lienlname">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" id="lienladdress">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2">
</p>
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
After (hate) comments (kidding) a js approach:
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
} else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
//js
container = document.getElementById('div1');
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
inputs[index].value = "";
}
}
}
<input type="radio" value="Yes" name="lien" id="lien" onchange="showhideForm(this.value);" />
<label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);" />
<label for="nolien">No Lien</label>
<div id="div1" style="display:none">
<div class="clearfix">
<p>
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" id="lienlname">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" id="lienladdress">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2">
</p>
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
I am trying to do show and hide div base on radio button click but it can not work perfect.
I am currently using javascript function to control the content display.
This is javascript code :
function udatabase() {
document.getElementById('ifCSV').style.display = "none";
}
function ucsv() {
document.getElementById('ifCSV').style.display = "block";
}
This is my radio button:
<input type="radio" name="data" onclick="udatabase()" id="udatabase"> Database
<input type="radio" name="data" onclick="ucsv()" id="ucsv"> CSV <br/>
<div id="ifCSV" style="display:none">
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
</div>
After click on csv, there is no response in html page.
Your javascript onclick function name cannot same with your id name inside input text. You should change one of the name.
Your html code here:
<input type="radio" name="data" onclick="udatabase()" id="udatabase"> Database
<input type="radio" name="data" onclick="ucsv()" id="ucsv"> CSV <br/>
After edited
<input type="radio" name="data" onclick="udatabase()" id="tdatabase"> Database
<input type="radio" name="data" onclick="ucsv()" id="tcsv"> CSV <br/>
This should be work properly after you change the name.
<script type="text/javascript">
window.onload = function() {
document.getElementById('ifTSH').style.display = 'none';
document.getElementById('ifUSD').style.display = 'none';
}
function yesnoCheck() {
var testA=document.getElementById('testAmount').value;
var dola=document.getElementById('fxd').value;
if (document.getElementById('s').checked) {
if(testA>50000){
document.getElementById('ifTSH').style.display = 'block';
document.getElementById('ifUSD').style.display = 'none';
document.getElementById("ifUSD1").removeAttribute("required");
}
else{
document.getElementById('ifTSH').style.display = 'none';
document.getElementById('ifUSD').style.display = 'none';
document.getElementById("ifUSD1").removeAttribute("required");
}
}
if (document.getElementById('d').checked) {
if((testA*dola)>50000){
document.getElementById('ifTSH').style.display = 'none';
document.getElementById('ifUSD').style.display = 'block';
document.getElementById('ifUSD1').setAttribute("required", "true");
}
else {
document.getElementById('ifTSH').style.display = 'none';
document.getElementById('ifUSD').style.display = 'none';
document.getElementById("ifUSD1").removeAttribute("required");
}
}
}