making the checkbox to display div - javascript

here am trying to display divs ClinicFieldSet and HospitalFieldset by selecting the given text boxes. If both are selected, both ClinicFieldset and HospitalFieldset should display and if one of the check box is selected it should show which div is selected.
The problem with my script is, when one of the checkboxes are clicked, both checkboxes are getting selected and it is not posible to uncheck them also. So please suggest me an idea to fix this problem :(
I used Javascript onClick in both checkboxes to apply on both of them.
<script type="text/javascript>
var clinic = document.getElementById('clinic');
var visit = document.getElementById('visit');
if((clinic.checked = true) && (visit.checked = true) )
{
document.getElementById('ClinicFieldSet').style.display='block';
document.getElementById('HospitalFieldSet').style.display='block';
}
else if((clinic.checked = true) && (visit.checked = false))
{
document.getElementById('ClinicFieldSet').style.display='block';
document.getElementById('HospitalFieldSet').style.display='none';
}
else if((clinic.checked = false) && (visit.checked = true))
{
document.getElementById('ClinicFieldSet').style.display='none';
document.getElementById('HospitalFieldSet').style.display='block';
}
else
{
document.getElementById('ClinicFieldSet').style.display='none';
document.getElementById('HospitalFieldSet').style.display='none';
}
HTML
<input type="checkbox" name="type" id="clinic" onClick="dispp();" >Clinic Practice
<input type="checkbox" name="type" id="visit" onClick="dispp();" >Visiting Hospital

In your if statement use the == equality operator.
The single = is used to assign a value, not test its equality.

May I suggest a revised approach (not using in-line click-handlers) with a slightly amended html, just to make the JavaScript somewhat more simple:
HTML:
<input type="checkbox" name="type" id="clinic" /><label for="clinic">Clinic Practice</label>
<input type="checkbox" name="type" id="hospital" /><label for="hospital">Visiting Hospital</label>
<div id="clinicInfo">
<h2>Clinic information</h2>
</div>
<div id="hospitalInfo">
<h2>Hospital information</h2>
</div>
JavaScript:
document.getElementById('hospitalInfo').style.display = 'none';
document.getElementById('clinicInfo').style.display = 'none';
var inputs = document.getElementsByTagName('input');
function dispp() {
if (this.checked) {
document.getElementById(this.id + 'Info').style.display = 'block';
}
else {
document.getElementById(this.id + 'Info').style.display = 'none';
}
}
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase() == 'checkbox') {
inputs[i].onchange = dispp;
}
}
JS Fiddle demo.

Try this
if(clinic.checked == true)
{
document.getElementById('ClinicFieldSet').style.display='block';
}
else
{
document.getElementById('ClinicFieldSet').style.display='none';
}
if(visit.checked == true)
{
document.getElementById('HospitalFieldSet').style.display='block';
}
else
{
document.getElementById('HospitalFieldSet').style.display='none';
}

var form=document.forms.add
form.elements.check.addEventListener('change',function(e) {
e.preventDefault()
var check=document.querySelector('.check')
if(check.checked=true)
{
document.querySelector('.inside').style.display='block'
}
else{
document.querySelector('.inside').style.display='none'
}
})

Related

Reveal additional info based on two (out of three) checkboxes JavaScript

I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Enable/disable button based on accepting the 2 checkbox conditions

I have gone through the stackoverflow regarding enable/disable button conditionally and was able to find some help but NOT EXACT what I was looking for.
Instead of 1 checkbox condition, I have 2 checkbox conditions. So unless if the two checkboxes have been accepted, the button should not be enabled.
Following is my html:
<input type="checkbox" id="f_agree" value="1" onchange="checked(this, 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checked('f_agree', this)"/>
<button type="submit" disabled="disabled" id="acceptbtn">Continue</button>
Following is javascript:
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.disabled = "";
} else {
myLayer.class = "button:disabled";
myLayer.disabled = "disabled";
};
}
I have tried like above, but it is not working. I don't know where I am going wrong.
it won't work because you are not removing that attribute disabled.
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
Update
use any other name then checked as it seems to be reserved and not working.
you also need to do getElementById for element1 and element2.
function checkedFunc(element1Id, element2Id) {
var myLayer = document.getElementById('acceptbtn');
var element1 = document.getElementById(element1Id);
var element2 = document.getElementById(element2Id);
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
<input type="checkbox" id="f_agree" value="1" onchange="checkedFunc('f_agree', 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checkedFunc('f_agree','f_agree2')"/>
<input type="button" value="check" id="acceptbtn" />
You can try the following code
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
With jQuery:
var btn;
var changed = function() {
//get the length of non checked boxes
var disbl = $('input[id^=f_agree]:not(:checked)').length;
btn.prop('disabled', disbl);//disable if true, else enable
};
$(function() {
btn = $('#acceptbtn');
$('input[id^=f_agree]').on('change', changed).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="f_agree" value="1" />1
<input type="checkbox" id="f_agree2" value="1" />2
<input type="button" id="acceptbtn" value="Submit" />
The problem is that there is a difference between the string "f_agree" and the node with id="f_agree".
Your code should work as expected with
checked(this, document.getObjectById('f_agree2'))
Much better would be however to avoid having a widget knowing about the other... I'd implement instead by adding a list of external rules that check all widgets:
function okSubmit() {
return (document.getElementById("f_agree").checked &&
document.getElementById("f_agree2").checked);
}
This is much easier to read/maintain and also scales better in case you need to add more conditions later. In the onchange of all the widgets just call a function that will enable/disable the submit button depending on the conditions.
Try this
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};
Try the below code -
var chk1 = document.getElementById('chk1');
chk1.addEventListener('click', checked, false);
var chk2 = document.getElementById('chk2');
chk2.addEventListener('click', checked, false);
function checked(){
if(chk1.checked && chk2.checked) {
document.getElementById('btn').removeAttribute('disabled');
} else {
document.getElementById('btn').setAttribute('disabled','disabled');
}
}
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<button id="btn" disabled >Button<button>
I tested it and it's working! Hope it helps u...

Javascript - Not Reversing the show/hide

I have created a fiddle
Would like to have the user hit 'yes' and it show the # field and then hit 'no' to hide it. Do I need another function on the 'no' to do this?
var empNumber, radios;
function showReqEmp() {
if (!radiosChecked()) {
empNumber.style.display = 'none';
} else {
empNumber.style.display = 'block';
}
}
function showReqEmp(id) {
var a = document.getElementById(id);
if (!radiosChecked())
a.style.display = 'none';
else
a.style.display = 'block';
}
function radiosChecked() {
var radios = document.getElementsByName('returning_employee');
for (var i = 0; i < radios.length; i++)
if (radios[i].checked) return true;
return false;
}
showReqEmp('requiredNum');
showReqEmp('requiredNumText');
<font color="Red">*</font>Returning Employee:</td>
<input type="radio" name="returning_employee" value="Yes" onclick="showReqEmp('requiredNum'); showReqEmp('requiredNumText')">Yes
<input type="radio" name="returning_employee" value="No" onclick="showReqEmp('requiredNumText'); showReqEmp('requiredNum')" />No
<lable id="requiredNumText" style="display:none"><font color="Red">*</font>Employee Number:</lable>
<lable id="requiredNum" style="display:none">
<input type="text" id="employee_number" name="employee_number" placeholder="123456789">
Ok so now I ran into this issue with the validation.
Fiddle2
The show/hide works but i cant get the validation to check if they entered data after hitting 'yes'
var numberExp = /^[0-9\-]+$/;
function validate()
{
if(document.newempRequest.returning_employee.checked && !(document.newempRequest.employee_number.value.match(numberExp)))
{
alert("Please provide the employee number");
document.newempRequest.employee_number.focus();
return false;
}
return true;
}
I have tried to alter the input tags to differ the yes/no but that breaks the show/hide
The HTML code is same as above.
Simply modify the radiosChecked function to return true only if the Yes checkbox is checked.
function radiosChecked() {
var radios = document.getElementsByName('returning_employee')[0];
return radios.checked;
}
The original Code:
var radios = document.getElementsByName('returning_employee');
for (var i = 0; i < radios.length; i++)
if (radios[i].checked) return true;
return false;
Would return true even if any of the check box in the group is checked. Hence the toggling would not happen.
You can do it CSS-only, without JS:
#requiredNum {
display: none;
}
#returning_employee_yes:checked ~ #requiredNum {
display: block;
}
*Returning Employee:
<input type="radio" name="returning_employee"
id="returning_employee_yes" value="Yes" />
<label for="returning_employee_yes">Yes</label>
<input type="radio" name="returning_employee"
id="returning_employee_no" value="No" />
<label for="returning_employee_no">No</label>
<label id="requiredNum">
*Employee Number:
<input type="text" id="employee_number"
name="employee_number" placeholder="123456789" />
</label>

too see if checkboxes have been checked javascript

Hallo
How would I go about in checking whether checkBox has been checked in javascript?
I C# it is simple enough
int selected = 0;
for (int loop = 0; loop < chkMeal.CheckedItems.Count; loop++)
{
selected++;
}
if (selected > 1)
{
MessageBox.Show("only one meal allowed", "Halt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
How could I do a simlar thing with javascript?
kind regards
Arian
For instance, if you give your checkboxes a class you can do something like this:
var myboxes = document.getElementsByClassName('myboxes');
for (var i=0; i<myboxes.length;i++) {
if (myboxes[i].checked) {
alert('Box number '+i+' is checked!');
}
}
Simply put, give your form a unique id attribute. Then, traverse HTMLFormElement.elements and check against HTMLInputElement.checked for a truthy value.
HTML:
<form id="foo" method="post" action="./">
<input type="checkbox" name="check_a" value="foo" />
<input type="checkbox" name="check_b" value="bar" />
<input type="checkbox" name="check_c" value="baz" checked />
</form>
JS:
var foo = document.getElementById("foo"), i = 0, el;
for(i;i<foo.elements.length;i++)
{
el = foo.elements[i];
if(el.nodeType === 1 && el.tagName === "INPUT" && el.type === "checkbox")
{
//element node, is an input element, is a checkbox
if(el.checked)
{
//checkbox is checked
}
}
el = null;
}
Bonus reference:
HTMLFormElement (via DOM Level 2)
HTMLInputElement (via DOM Level 2)
Using a little bit of jQuery:
$(function() {
$('form').submit( function() {
if ($('[name="chkMeal"]:checked').length > 1) {
// show an error
return false; // cancel submit
}
});
});

Categories

Resources