IF ELSE statement with && and || condition - javascript

I have a group of checkboxes (id = "first" id = "second") and the main checkbox (id = "main").
<input type='checkbox' id="main_button" onclick="Indeterminate()"><label for="main_button">Main checkbox of group</label>
<input type='checkbox' id="first" onclick="Indeterminate()"><label for="first">First thing</label>
<input type='checkbox' id="second" onclick="Indeterminate()"><label for="second">Second thing</label>
If one or more of the group checkbox checked then the main have indeterminate condition. If all checked then the main checkbox have also checked condition.
function Indeterminate() {
if (document.getElementById('first').checked || document.getElementById('second').checked) {
document.getElementById('main_button').indeterminate = true;
} else if (document.getElementById('first').checked && document.getElementById('second').checked) {
document.getElementById('main_button').checked;
} else {
document.getElementById('main_button').indeterminate = false;
}
}
In my IF ELSE statement, conditions IF and ELSE works, but there is something wrong with ELSE IF. Probably doing a simple mistake or? Thank you!
JSFiddle example

var main = document.getElementById('main_button');
var first = document.getElementById('first');
var second = document.getElementById('second');
function Indeterminate() {
if (first.checked && second.checked) {
main.checked = true;
main.indeterminate = false;
} else if (first.checked || second.checked)
main.indeterminate = true;
else
main.indeterminate = false;
}
<input type='checkbox' id="main_button" onclick="Indeterminate()">
<label for="main_button">Main checkbox of group</label>
<input type='checkbox' id="first" onclick="Indeterminate()">
<label for="first">First thing</label>
<input type='checkbox' id="second" onclick="Indeterminate()">
<label for="second">Second thing</label>

Your && code is right, but it's the && situation is apart of you || code, so When || is not true, the && will not true too. Just change their sequence.

I think the problem is that you are getting the meaning of || wrong. It means or in the sense that either the left or the right expression is true - or both!
Therefore, your else if will never be called, because if a.checked && b.checked is true, then a.checked || b.checked will always be true as well, and the if will be executed before the else if is even checked.
Therefore, the correct solution is:
function Indeterminate() {
if (document.getElementById('first').checked && document.getElementById('second').checked) {
document.getElementById('main_button').checked;
} else if (document.getElementById('first').checked || document.getElementById('second').checked) {
document.getElementById('main_button').indeterminate = true;
} else {
document.getElementById('main_button').indeterminate = false;
}
}
Here, you first check for the more specific condition a.checked && b.checked. Only if that condition is not true, the weaker condition a.checked || b.checked is evaluated.

As commented before, you should move && before ||.
Reason for this is if first is selected or both is selected, first.checked || second.checked will always be true. Only situation when || will fail is when both are unchecked, and then && will also fail.
JSFiddle
Updated Code
function Indeterminate() {
var first = document.getElementById('first').checked;
var second = document.getElementById('second').checked
var main = document.getElementById('main_button');
if (first && second) {
main.indeterminate = false;
main.checked = true
} else {
main.checked = main.indeterminate = first || second
}
}
<input type='checkbox' id="main_button" onclick="Indeterminate()">
<label for="main_button">Main checkbox of group</label>
<br>
<input type='checkbox' id="first" onclick="Indeterminate()">
<label for="first">First thing</label>
<br>
<input type='checkbox' id="second" onclick="Indeterminate()">
<label for="second">Second thing</label>
As commented by Bekim Bacaj, I have updated my code. JSFiddle

Related

.checked always returns true?

I'm using vanilla js, and I'm stumped because there's very little code here, so I'm not sure where the problem lies. It may be a misunderstanding on my part on how the attribute works.
function changeState() {
const self = event.target
const parent = event.path[1]
if (self.type == "radio") {
console.log(self.id + " is " + self.checked)
}
}
<div id="usernames_buttons">
<input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked>
<label for="usernames-bl">BL</label>
</input>
<input type="radio" name="usernames" id="usernames-wl" onclick="changeState()">
<label for="usernames-wl">WL</label>
</input>
<button data-toggle onclick="changeState()">OFF</button>
</div>
I paired everything down to just this code and ran it in a code pen to test, and the console.log will return true regardless of which option I am clicking. The expectation is that usernames-bl would return true and -wl would return false, but they return true whether the checked attribute is there or not.
You are invoking the changeState() on every click and i guess, as its a radio button, which will always give checked 'true' on click
I think you are doing it right minus the "Off" button should un-check both.. so I added this block:
if (self.type != "radio") {
document.getElementById("usernames-wl").checked = false;
document.getElementById("usernames-bl").checked = false;
}
function changeState() {
const self = event.target
const parent = event.path[1]
if (self.type != "radio") {
document.getElementById("usernames-wl").checked = false;
document.getElementById("usernames-bl").checked = false;
}
console.log("usernames-wl is " + document.getElementById("usernames-wl").checked)
console.log("usernames-bl is " + document.getElementById("usernames-bl").checked)
}
<div id="usernames_buttons">
<input type="radio" name="usernames" id="usernames-bl" onclick="changeState()" checked/>
<label for="usernames-bl">BL</label>
<input type="radio" name="usernames" id="usernames-wl" onclick="changeState()"/>
<label for="usernames-wl">WL</label>
<button data-toggle onclick="changeState()">OFF</button>
</div>

How can I apply CSS to a link if at least one input is not original, and undo that change if all inputs are original?

I have a bunch of checkboxes, radio buttons, and text fields on my page. They all have '_boom' appended to the end of the id. I want to detect if any one of these inputs is not its original value, and if so, apply CSS to a button called 'save' on the page. Then, if the user reverts any changes they made and all inputs have their original values, I want to undo the CSS.
I've gotten close with the code below. But let's say I check 3 checkboxes. Upon checking the 1st box, the CSS changes. Good! I check the 2nd and 3rd boxes. The CSS stays the same. Good! But then I uncheck ONE of the boxes, and the CSS reverts. Bad! The CSS should only revert if I undo every change.
$('[id*="_boom"]').change(function() {
var sType = $(this).prop('type'); //get the type of attribute we're dealing with
if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
var originalCheckedState = $(this).prop("defaultChecked");
var currentCheckedState = $(this).prop("checked");
if(currentCheckedState !== originalCheckedState){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
if( sType === "text" ){ //text type
var originalValue = $(this).prop("defaultValue");
var currentValue = $(this).val();
if(currentValue !== originalValue){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
});
#save {
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
There are many possible improvements in your code to make it cleaner and standardized. Things like instead of relying on id you should consider class attribute and all... but I will not revamp your code. Here's the solution to your existing code.
The idea is loop through all the form elements and if atleast one of the elements is different than its default value then set the flag and come out of the loop.
At the end, check for that flag and set the css accordingly.
For this, I have enclosed your elements into a form form1.
$("#form1 :input").change(function() {
var changed = false;
formElems = $("#form1 :input");
for(i=0;i<formElems.length; i++){
var sType = $(formElems[i]).prop("type");
if(sType === "checkbox" || sType === "radio"){
if($(formElems[i]).prop("defaultChecked") !== $(formElems[i]).prop("checked")){
changed = true;
break;
}
}else if(sType === "text"){
if($(formElems[i]).prop("defaultValue") !== $(formElems[i]).val()){
changed = true;
break;
}
}
}
if(changed){
$("a#save").css("color","#CCCCCC");
}else{
$("a#save").css("color","black");
}
});
And here is your form
<form id="form1">
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
</form>
The problem is, when one of them change to its original value, it doesn't mean there is no change.
So, in your else code block, you should check all the inputs, if all of them are the original values, remove the 'save' class from the button, otherwise, keep it.
var isChanged = function ($element) {
var sType = $element.prop('type');
if (sType === "checkbox" || sType === "radio") {
var originalCheckedState = $element.prop("defaultChecked");
var currentCheckedState = $element.prop("checked");
if (currentCheckedState !== originalCheckedState) {
return true;
} else {
return false;
}
} else if( sType === "text" ) {
var originalValue = $element.prop("defaultValue");
var currentValue = $element.val();
if (currentValue !== originalValue) {
return true;
} else {
return false;
}
}
};
var $inputs = $('[id*="_boom"]');
var isAnyChanged = function () {
$inputs.each(function () {
if (isChanged($(this))) {
return true;
}
});
return false;
};
$inputs.change(function () {
if (isChanged($(this))) {
$("a#save").css("color","#CCCCCC");
} else if (!isAnyChanged()) {
$("a#save").css("color","black");
}
});

Radio Button not Working in ie

I have 4 radio button in my form, once i submit the form any of the radio button should checked, if not a alert message will be displayed. its working properly in chrome, firefox, but in ie one i checked the radion it always showing the alert so i cant submit the form, i have given my code below please help me
PHP:
<form action="user_register.php" method="POST" name="myForm" onsubmit="return validateForm()" enctype="multipart/form-data">
<label>USERNAME:</label></td>
<input type="text" name="username" class="regtext" required/>
<label>RESIDING CITY:</label></td>
<input type="text" name="city" class="regtext" required/>
<label>I'M A</label>
<label>ARTIST &nbsp <input type="radio" value="1" name="user_type" > </label>&nbsp
<label>MODEL &nbsp <input type="radio" value="2" name="user_type"></label>&nbsp
<label>COMPOSER &nbsp <input type="radio" value="3" name="user_type" ></label>&nbsp<br>
<label>BEAT MAKER &nbsp <input type="radio" value="4" name="user_type" ></label>&nbsp
<label>NONE &nbsp <input type="radio" value="0" name="user_type" ></label>
<label> <input type="checkbox" value="1" name="letter" > &nbsp I WOULD LIKE TO RECEIVE YOUR NEWSLETTER</label>
</div>
<div class="mainhead">
<input type="submit" name="register" class="submit" value="SEND AND REGISTER NOW">
</div>
</form>
JS:
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
Problem is that for IE, document.forms["myForm"]["user_type"] is an HTMLCollection and has no value
Solution is to change
var user_type = document.forms["myForm"]["user_type"].value;
to
var user_type = document.querySelector('form[name="myForm"] input[name="user_type"]:checked').value;
What i observed is :
No name province present in code (what you gave). If you include it here, it will not work.
<script type="text/javascript">
function validateForm() {
var province = document.forms["myForm"]["province"].value;
if (province == 0 ) {
alert("Select Province");
document.myForm.province.focus()
return false;
}
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
After removing province validation. It started working.
<script type="text/javascript">
function validateForm() {
var user_type = document.forms["myForm"]["user_type"].value;
if (user_type == null || user_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.forms["myForm"]["letter"].value;
if (letter == null || letter == "") {
alert("Select that you want to receive news letter");
return false;
}
}
</script>
So, as Mr Rayon Dabre said "There is no element having name as province". So, i also agree with him. Remove province validation from validateForm() function (as it is not used in <from></form>)
This code should do the trick:
function validateForm() {
var user_type = document.getElementsByName('user_type');
var u_type = '';
for (var i = 0, length = user_type.length; i < length; i++) {
if (user_type[i].checked) {
// do whatever you want with the checked radio
u_type = user_type[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
if (u_type == "") {
alert("Select Who You are");
return false;
}
var letter = document.getElementsByName('letter')[0].checked;
if (letter == "" || letter == undefined) {
alert("Select that you want to receive news letter");
return false;
}
}

Cannot set the value properly in javascript

I've 6 following radio buttons
<input type="text" id="status" name="status">
<input type="radio" name="orderReceivingKeysPresent" id="orderReceivingKeysPresent_Y" value="1" onclick="checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingKeysPresent" id="orderReceivingKeysPresent_N" value="0" onclick="checkKeyAndTitle(this);"> No
<input type="radio" name="orderReceivingTitlePresent" id="orderReceivingTitlePresent_Y" value="1" onclick="checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingTitlePresent" id="orderReceivingTitlePresent_N" value="0" onclick="checkKeyAndTitle(this);"> No
<input type="radio" name="orderReceivingReturnToOwner" id="orderReceivingReturnToOwner_Y" value="1" onclick="hideAndShowReturnToOwner(this); checkKeyAndTitle(this);"> Yes
<input type="radio" name="orderReceivingReturnToOwner" id="orderReceivingReturnToOwner_N" value="0" onclick="hideAndShowReturnToOwner(this); checkKeyAndTitle(this);" checked="checked"> No
No I'm using javascript for assiging values. I've created javascript function but it isn't working properly and I can't figure it out. How to do it?
function checkKeyAndTitle(getObj) {
if(getObj.name == "orderReceivingKeysPresent") {
if(getObj.value == "1") {
$("#status").val('Delivered');
} else {
$("#status").val('Missing Keys');
}
}
else {
if(getObj.value == "1") {
$("#status").val('Delivered');
} else {
$("#status").val('Missing Title');
}
}
}
Now orderReceivingReturnToOwner is checked to no by default.
When I click at orderReceivingKeysPresent to yes and orderReceivingTitlePresent to no then status should be Missing Title and when orderReceivingKeysPresent no and orderReceivingTitlePresent yes status should be Missing Keys and when both are yes status should be Delivered and also check this one to when orderReceivingReturnToOwner yes status should be Return To Owner. Help suggest me how to do it.
$("input[type='radio']").on("click", function () {
var keyRadioVal = $('input:radio[name=orderReceivingKeysPresent]:checked').val();
var titleRadioVal = $('input:radio[name=orderReceivingTitlePresent]:checked').val();
var ownerRadioVal = $('input:radio[name=orderReceivingReturnToOwner]:checked').val();
if (ownerRadioVal == 1) {
$("#status").val('Return To Owner');
} else if (keyRadioVal == 1 && titleRadioVal == 0 && ownerRadioVal == 0) {
$("#status").val('Missing Title');
} else if (titleRadioVal == 1 && keyRadioVal == 0 && ownerRadioVal == 0) {
$("#status").val('Missing Keys');
} else if (titleRadioVal == 1 && keyRadioVal == 1 && ownerRadioVal == 0) {
$("#status").val('Delivered ');
} else {
$("#status").val('Missing Keys');
}
});
what i had done is getting value of each radio button which is selected on selection change of every single radio button and check all 3 case.
rest in all case Missing key will be shown that you can accordingly.

Jquery Conditional Statements for Multiple Checkbox Values

I'm new to posting/stackoverflow, so please forgive me for any faux pas. I have multiple buttons and checkboxes that I need to store the values of to place into conditional statements.
The HTML code:
<h1>SECTION 1: GENDER</h1>
<p>What is your gender?</p>
<input type="button" onclick="storeGender(this.value)" value="Male"/>
<input type="button" onclick="storeGender(this.value)" value="Female"/>
<hr />
<h1>SECTION 2: AGE</h1>
<p>What is your age?</p>
<input type="button" onclick="storeAge(this.value)" value="18–22"/>
<input type="button" onclick="storeAge(this.value)" value="23–30"/>
<hr />
<h1>SECTION 3: TRAITS</h1>
<h3>Choose Two:</h3>
<form>
<input name="field" type="checkbox" value="1"/> Casual <br />
<input name="field" type="checkbox" value="10"/> Cheerful <br />
<input name="field" type="checkbox" value="100"/> Confident <br />
<input name="field" type="checkbox" value="1000"/> Tough <br />
<input type="button" id="storeTraits" value="SUBMIT" /> <br />
</form>
<hr />
<h2>Here is what I suggest</h2>
<p id="feedback">Feedback goes here.</p>
jQuery code:
// set up variables
var gender;
var age;
var string;
$(document).ready(function() {
startGame();
$("#storeTraits").click( function() {
serializeCheckbox();
}
); }
);
function startGame() {
document.getElementById("feedback").innerHTML = "Answer all the questions.";
}
function storeGender(value) {
gender = value;
}
function storeAge(value) {
age = value;
}
function serializeCheckbox() {
// clear out any previous selections
string = [ ];
var inputs = document.getElementsByTagName('input');
for( var i = 0; i < inputs.length; i++ ) {
if(inputs[i].type == "checkbox" && inputs[i].name == "field") {
if(inputs[i].checked == true) {
string.push(inputs[i].value);
}
}
}
checkFeedback();
}
//Limit number of checkbox selections
$(function(){
var max = 2;
var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function(){
var current = checkboxes.filter(':checked').length;
checkboxes.filter(':not(:checked)').prop('disabled', current >= max);
});
});
function checkFeedback() {
if(gender == "Male") {
if (age == "18–22" && string == 11){
document.getElementById("feedback").innerHTML = "test1";
} else if (age == "18–22" && string == 110){
document.getElementById("feedback").innerHTML = "test2";
} else if (age == "18–22" && string == 1100){
document.getElementById("feedback").innerHTML = "test3";
} else if (age == "18–22" && string == 101){
document.getElementById("feedback").innerHTML = "test4";
}
}
}
I found this code on JSFiddle: http://jsfiddle.net/GNDAG/ which is what I want to do for adding together my trait values. However, when I try to incorporate it my conditional statements don't work. How do I add the code from the jsfiddle example and get the conditional statements to work? Thank you!
You need an integer, not a string array. Here's the code you need:
var traits = 0;
$('input[name=field]:checked').each(function () {
traits += parseInt($(this).val(), 10);
});
This will set the "traits" variable to an integer like 1, 11, 101, or 1001.
BTW: The second parameter to parseInt() is the base.
But a few suggestions:
Don't use "string" as a variable name.
Use radio buttons for gender and age.
Put all the input elements in the form.
Have one button that submits the form.
Attach a handler to the form submit event, and do your processing in that function, but call e.preventDefault() to prevent the form from submitting to the server. Alternatively, you could have the single button not be a submit button and attach an on-click handler to it.
Here's a jsfiddle with the code above and all the suggestions implemented.

Categories