I've got the following jQuery script correctly displaying and checking two hidden checkboxes. The only problem is that I'm trying to hide both of these checkboxes but when I uncheck my visible checkbox they remain checked?
<input type="checkbox" name="JobType[]" class="visiChk" id="nineteen" value="19" <?php echo (isset($_GET["JobType"]) && !empty($_GET["JobType"]) && in_array("19", $_GET["JobType"])) ? "checked": ""; ?> /> Plumbing
<label id="hiddenLabel" style="display:none">
<input type="checkbox" name="JobType[]" class="visiChk" id="seventeen" value="17" <?php echo (isset($_GET["JobType"]) && !empty($_GET["JobType"]) && in_array("17", $_GET["JobType"])) ? "checked": ""; ?> /> Plumbing
<input type="checkbox" name="JobType[]" class="visiChk" id="eighteen" value="18" <?php echo (isset($_GET["JobType"]) && !empty($_GET["JobType"]) && in_array("18", $_GET["JobType"])) ? "checked": ""; ?> /> Plumbing
</label>
<script>
// update if any are checked/unchecked
$('.visiChk').change(function() {
var hiddenLabel = $('#hiddenLabel')[0];
var seventeen = $('#seventeen')[0];
var eighteen = $('#eighteen')[0];
// Are any of them checked ?
if ($('.visiChk:checked').length > 0) {
hiddenLabel.style.display = 'block';
seventeen.checked = true;
eighteen.checked = true;
} else {
hiddenLabel.style.display = 'none';
seventeen.checked = false;
eighteen.checked = false;
}
});</script>
There's a logical error occurring here that might not be readily obvious with the hidden fields. When you are checking to see if any of the checkboxes are marked, you're checking all of them, even the hidden ones.
So, walk through the cycle once more. The page loads, no checkboxes have been checked. A user checks the visible one. All three are checked. The user then unchecks only the visible one. Your logic check here
if ($('.visiChk:checked').length > 0) {
is looking at all three of them. Are there any checked? Yes, the two hidden ones still are! So, all three will be set to checked again. You'll need a way to only look at the visible checkbox and then update the invisible ones accordingly. A unique ID or different class would work well.
I wrote up an example jsfiddle that helps to illustrate what's going on. Instead of hiding the checkboxes, I set the font color to grey to show which ones should actually be hidden.
https://jsfiddle.net/sm1215/d9geaog4/1/
Edit: Also, I set up a console log to show the result of the logic check going on. When the page first loads (no checkboxes are checked) and the user checks one, it evaluates to 1. Uncheck the visible one, and it evaluates to 2 - showing the 2 hidden checkboxes are still being counted.
Edit 2: Here's the code from the jsfiddle for reference in case the fiddle is ever lost.
HTML
<input type="checkbox" name="JobType[]" id="nineteen" class="visiChk" value="19" /> Plumbing
<label id="hiddenLabel" style="color:silver; /*display:none*/">
<input type="checkbox" name="JobType[]" class="visiChk" id="seventeen" value="17" /> Plumbing
<input type="checkbox" name="JobType[]" class="visiChk" id="eighteen" value="18" /> Plumbing
</label>
JS
// update if any are checked/unchecked
$('.visiChk').change(function() {
var hiddenLabel = $('#hiddenLabel')[0];
var seventeen = $('#seventeen')[0];
var eighteen = $('#eighteen')[0];
// Are any of them checked ?
console.log($('#nineteen:checked').length);
if ($('#nineteen:checked').length > 0) {
hiddenLabel.style.display = 'block';
seventeen.checked = true;
eighteen.checked = true;
} else {
// Commenting this out so the hidden fields stay visible for demo purposes
//hiddenLabel.style.display = 'none';
seventeen.checked = false;
eighteen.checked = false;
}
});
Related
I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}
I created a toggle switch checkbox and aplied the logic below:
1] If user clicks on toggle switch class="os_section-slider" the script will check if the input containing element's name is checked.
1-A] If the element is checked then change it to UNchecked and add that element into array named os_tagsToRemove
1-B] If the element is UNchecked then change it to checked and add that element into array named os_tagsToAdd
HTML
<span class="os_section-name">first</span>
<input type="checkbox" class="os_section-check" id="first" checked="checked">
<label class="os_section-slider" for="first"></label>
<div class="line-space-between"></div>
<span class="os_section-name">second</span>
<input type="checkbox" class="os_section-check" id="second">
<label class="os_section-slider" for="second"></label>
JS
$(".os_section-slider").click(function() {
if($(this).prev().is(":checked")) { //if checked
$(this).prev().attr("checked", false);
var os_tagName = $(this).prev().attr("id").toString();
os_tagsToRemove.push(os_tagName);
os_tagsToAdd.splice($.inArray(os_tagName, os_tagsToAdd),1);
} else { //if unchecked
$(this).prev().attr("checked", true);
var os_tagName = $(this).prev().attr("id").toString();
os_tagsToAdd.push(os_tagName);
os_tagsToRemove.splice($.inArray(os_tagName, os_tagsToRemove),1);
}
});
My problem is, when my page reloads and my toggle switch appears in a modal box and I try to click on the switcher button I have to click 2 times until the checked attribute is added/removed.
The first click always only pushes the value into the array or removes it from the array but doesn't apply $(this).prev().attr("checked", true); nor $(this).prev().attr("checked", false);.
But after the second click on each switcher button, everything from that moment works fine.
Add this to load your add/remove arrays:
// Onload remove array fill
$("[type='checkbox']").each(function(){
if( $(this).is(":checked") ){
os_tagsToRemove.push($(this).attr("id"));
}else{
os_tagsToAdd.push($(this).attr("id"));
}
});
Then, your logic was all reversed.
First, when you click on the label, which is defined as for="anID", the checked state of the coresponding checkbox already changes. You do not have to script that.
Then, when you look if it is checked, you have to know that this verification is made AFTER the checkbox state has changed. So I reversed your if conditions.
var os_tagsToAdd = [];
var os_tagsToRemove = [];
$(".os_section-slider").click(function() {
console.clear();
var os_tagName = $(this).prev().attr("id");
//if checked AFTER the click
if($(this).prev().is(":checked")) {
if($.inArray(os_tagName, os_tagsToAdd) == -1){
os_tagsToAdd.push(os_tagName);
}
os_tagsToRemove.splice($.inArray(os_tagName, os_tagsToRemove),1);
//if unchecked AFTER the click
} else {
if($.inArray(os_tagName, os_tagsToRemove) == -1){
os_tagsToRemove.push(os_tagName);
}
os_tagsToAdd.splice($.inArray(os_tagName, os_tagsToAdd),1);
}
console.log( os_tagsToAdd );
console.log( os_tagsToRemove );
});
// Onload remove array fill
$("[type='checkbox']").each(function(){
if( $(this).is(":checked") ){
os_tagsToRemove.push($(this).attr("id"));
}else{
os_tagsToAdd.push($(this).attr("id"));
}
});
console.log( os_tagsToAdd );
console.log( os_tagsToRemove );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="os_section-name">first</span>
<input type="checkbox" class="os_section-check" id="first" checked="checked">
<label class="os_section-slider" for="first">Label</label>
<div class="line-space-between"></div>
<span class="os_section-name">second</span>
<input type="checkbox" class="os_section-check" id="second">
<label class="os_section-slider" for="second">Label</label>
I have a problem with validating the form in function validate() method. This line of code:
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
is being skipped because one or both of the conditions are false, but I'm not sure which one and as well as if the condition is proper to execute. I was thinking that radios[i].value == "yes" will correspond to the value attribute of that input radio button (In other words, the correct answer regarding that question).
When the submit button is clicked, I simply want javascript to tell me whether it's correct or not and to check if the radio button is checked.
Problem: I checked in the radio button, when submit button is clicked the alert for Please make sure you answer every question pops up 3 times and after that displays that I have the correct answer.
Here's the full code:
JavaScript:
// called when "Take Quiz" button is clicked
function takeQuiz()
{
// hide the intro
document.getElementById('intro').style.display = 'none';
// display the quiz
document.getElementById('message').style.overflow = 'auto';
document.getElementById('quiz').style.visibility = 'visible';
document.getElementById('gl_banner').style.display = 'block';
document.getElementById('gl_banner').style.visibility = 'visible';
}
//document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz()
{
var radios; // access elements by object name (DOM)
var i; // int variable
var right; // boolean variable to determine correct answer
radios = document.getElementById('question1').getElementsByTagName('input');
/*radios = document.getElementById('question2').getElementsByTagName('input');
radios = document.getElementById('question3').getElementsByTagName('input');
radios = document.getElementById('question4').getElementsByTagName('input');
radios = document.getElementById('question5').getElementsByTagName('input');*/
right = true;
// loop to check each radio button for validation
for(i = 0; i < radios.length; i++)
{
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
{
right = true;
}
else if(radios[i].checked == false)
{
right = false;
alert("Please check to make sure you have answered every question.");
}
}
if(right)
{
alert("You have answered correctly!");
}
else
{
alert("Wrong answer");
}
}
HTML Code:
<div id="message" style="overflow:hidden;"><div id="intro">Why not go ahead and take the quiz to test your knowledge based on what you've learned in Smartphone Photography.
There are only 5 questions surrounding the content of this site.
<br/>
<button id="takeQuiz" type="button" name="name" onclick="takeQuiz()" style="cursor:pointer;">Take Quiz!</button></div>
<div id="gl_banner" style="display:none; visibility:hidden;">Good Luck! :)</div>
<form id="quiz" action="#" method="post" style="visibility:hidden;" autocomplete="off">
<!--QUIZ-->
<h3>1. How many percent of modern camera phones use CMOS?</h3>
<div id="question1">
<input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
<label for="question-1-answers-A">A) 20%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
<label for="question-1-answers-B">B) 80%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
<label for="question-1-answers-C">C) 50%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-D" value="yes" />
<label for="question-1-answers-D">D) 90%</label>
</div>
**Edited for a pure javascript solution.
I got the function to get the select value from this post.
I don't think you need to do a loop here, as you only actually need to check one value- the value of the checked radio.
At the moment your looping through all the radios, so you'll always get three wrong answers.
**Edited again to fix some code errors. I have tested the following, it is working for me.
function getRadioValue(name) {
var group = document.getElementsByName(name);
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz(){
right = true;
radio = getRadioValue("question-1-answers");
if(!radio.length) {
right = false;
alert("Please check to make sure you have answered every question.");
return;
}
if(radio == 'yes')
{
alert("You have answered correctly!");
}
else {
right = false;
alert("Wrong answer");
}
}
I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});
I have 2 radio button with 2 group.
The structure is like this
Main Radio 1
Main Radio 2
Under Main Radio 2, there's two more sub radio button.
Main Radio 1
Main Radio 2
Sub Radio 1
Sub Radio 2
What am I doing is, in default stage, it will only show Main Radio 1 and Main Radio 2 button. When choose Main Radio 2, two sub radio button of Main Radio 2 appear.
When choose back to Main Radio 1, it will hide the list of Main Radio 2.
The one that I want to achieve is,
When click Main Radio 1, the selection that I made for Sub Radio 1 or Sub Radio 2, want to be uncheck / reset too.
I tried with this javascript, but no success.
document.getElementById("subradiobuttons").reset();
Please kindly help me the solutions. Thank you.
With Regards,
I think the best approach for a simple task like this does not needs a full JavaScript library like jQuery.
document.getElementById("main2").addEventListener("click", function()
{
document.getElementById("subCheckButtons").style.opacity = 1;
}, false);
document.getElementById("main1").addEventListener("click", function()
{
document.getElementById("subCheckButtons").style.opacity = 0;
document.getElementById("sub1").checked = false;
document.getElementById("sub2").checked = false;
}, false);
<input type="radio" id="main1" name="main" />
<input type="radio" id="main2" name="main" />
<div id="subCheckButtons" style="opacity:0;">
<input type="radio" id="sub1" name="sub" class="subCheck" />
<input type="radio" id="sub2" name="sub" class="subCheck" />
</div>
Or see the fiddle.
Here is another approach that will reset all inputs to their default position if someone clicks on "Main Radio 1."
//Clear all inputs.
function clearInputs(form) {
"use strict";
//Gather all inputs within selected form.
const inputs = form.querySelectorAll("input");
//Clear the inputs.
inputs.forEach(function (input) {
if (input.hasAttribute("checked") === true) {
input.checked = true;
} else {
input.checked = false;
}
});
}
//Monitor "Main Radio 1" for clicks.
function monitorMainRadio1() {
"use strict";
const form = document.getElementById("form");
const mainRadio1 = document.getElementById("main-radio1");
mainRadio1.addEventListener("click", function () {
clearInputs(form);
});
}
//Invoke the monitorMainRadio1 function.
monitorMainRadio1();
Not tested this but...
<input type="radio" onclick="document.getElementById("subradiobuttons").Checked = false;" />
Or you could call a Javascript function to do a bit more work/logic
This page has what you need
It is much, much quicker to do this with jQuery than JavaScript. I recommend you do something like this;
Give the radio boxes something like this
<input type="radio" name="main1">
<input type="radio" name="main2">
<input type="radio" name="sub">
<input type="radio" name="sub">
Then with jQuery you can do this
$('input[name=main1]').on('click', function() {
$('input[name=sub]').attr('checked', false);
});
I've assumed here that you've figured out a way to hide the sub radio buttons.
See a fiddle of this here
Also, make sure that you include jQuery at the top of the <script></script> tags containing this code.
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
Reset the radiobutton or RadiobuttonList in the form:
private void ResetFormControlValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormControlValues(c);
}
else
{
switch ((c.GetType().ToString()))
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)c).SelectedIndex = 0;
break;
}
}
}
}