If statement executing both if and else - javascript

I'm building a web app that converts Galloons to Liters and vise versa. Got one textbox to enter gallon/litters, the user selects on a radio button what they want to convert too. Now the problem arises when validating the input:
for liters it must be Greater than 0 but less than 1000 for the gallons it must be greater than 0 but less than 4000. So if I've selected liters it must validate only liters but both validations are coming up. Here's my code:
Form:
<body onload="setup()">
<div data-role="page">
<div style="padding: 20px;">
<div data-role="fieldcontain">
<input type="number" id="temperature" name="temperature">
<label id="label">Gallons</label>
</div>
<fieldset data-role="controlgroup">
<legend>Convert to:</legend>
<input type="radio" name="units" id="Gallons" value="Gallons"
onclick="setUnits('Liters')">
<label for="Gallons">Gallons</label>
<input type="radio" name="units" id="Liters" value="Liters"
checked="checked" onclick="setUnits('Gallons')">
<label for="Liters">Liters</label>
</fieldset>
<input type="button" onclick="convert()" value="Convert">
<p id="answer"></p>
</div>
</div>
</body>
JavaScript:
function setup()
{
var cType;
setUnits("Gallons");
cType = "Gallons";
document.getElementById("Gallons").onclick =
function () {
cType="";
cType="Liters";
setUnits("Liters");
CheckInput(cType);
};
document.getElementById("Liters").onclick =
function () {
cType="";
cType="Gallons";
setUnits("Gallons");
CheckInput(cType);
};
CheckInput(cType);
}
function setUnits(unit) {
var label = document.getElementById("label");
label.innerHTML = unit;
}
function CheckInput(cType) {
var CheckInputcType= cType;
var angleInput = document.getElementById("temperature");
if(CheckInputcType.localeCompare("Gallons")==0)
{
angleInput.addEventListener("blur",validateG);
}
else(CheckInputcType.localeCompare("Liters")==0)
{
angleInput.addEventListener("blur",validateL);
}
}
function validateL(){
var angleInput = document.getElementById("temperature");
if (angleInput.value >= 1000 || angleInput.value<=0)
{
alert('Liters must be between 0 and 1000');
angleInput.value = "";
}
}
function validateG() {
var angleInput = document.getElementById("temperature");
if (angleInput.value >= 4000 || angleInput.value<=0)
{
alert('Gallons must be between 0 and 4000');
angleInput.value = "";
}
}

You have a problem with your method CheckInput(cType), because every time you click on Galons or liters radio button you are adding a new listener event on temperature input.
Just simply create one listener and verify radio state on that validator method.

Related

How to change the value of a previous check box that has been selected in JQuery?

Here is what I'm trying to do.
I have the ability to create a form when there is an option to create one in Javascript.
Here is an option to add an address:
<i class="fas fa-plus-circle"></i> <span class="newUrlText">add new address
Here is the form in question:
<input type="text" class="form-control" id="new-address-1-%ID%" name="new-address-1-%ID%" placeholder="Address Line 1">
<input type="text" class="form-control" id="new-address-2-%ID%" name="new-address-2-%ID%"
placeholder="Address Line 2">
<label for="message" class="control-label"><span class="billable-text"><?php _e('Primary Address'); ?></span></label>
<label class="switch" for="primary-%ID%" style="margin-left: 10px;top: 10px;">
<input type="checkbox" class="primary-%ID%" name="primary-%ID%" id="primary-%ID%" />
<div class="slider round gray"></div>
</label>
Here is the javascript that generates the form:
<script language="javascript">
var newAddressIndex = 1;
var addressarray = [];
function addNewAddress() {
var container = getElement("addressContainer");
addressarray.push(newAddressIndex);
var htmlAddress = '<?php echo addslashes(App_String::stripBreaksTabsMultipleWhitespace($newAddress)); ?>';
htmlAddress = htmlAddress.replace(/%ID%/g, newAddressIndex);
var node = document.createElement("div");
node.innerHTML = htmlAddress;
container.appendChild(node);
$('#newAddressCount_'+newAssetIndex).val(newAssetIndex);
++newAddressIndex;
test(addressarray);
}
What I'm trying to do is the following:
If the user selects the checkbox and then decides to select the next checkbox, I would like to change the previous checkbox from selected to no selected.
How would I go about doing that?
Thank you
I found a solution:
What I did was, that I created a function to get the current value of the checkboxes like this:
getAddrValue(addressarray);
Then within the function the follwoing:
function getAddrValue (addressarray) {
$('#primary-'+index).change(function() {
var checked = this.checked ? 1 : 0;
prevCheckbox = index-1;
if (checked == 1) {
if (document.getElementById('primary-'+prevCheckbox) !== null ) {
let inputs = document.getElementById('primary-'+prevCheckbox);
inputs.checked = false;
}
}
});
}

How can I save a total score in localstorage each time a checkbox is checked

I've built a small game using checkboxes with images. When the user comes across the item in the picture they select the checkbox and the message changes on screen. Because this is a tourist guide website and game, the user will leave the page to look at other pages, selecting the pictures as they come across the item. Therefore I needed to save the checked boxes in localstorage so that the data persists. I have some javascript that dsave the checked boxes.
Each picture has a value and when the image is clicked it adds to an overall total. I can't get this total to persist if the page is refreshed or closed and reopened.
My javascript for calculating the total and storing the checkboxes is below.
$('.dp-spotter-switch input[type="checkbox"]').click(function () {
if (!$(this).is(':checked')) {
$(this).parent('.dp-spotter-switch').removeClass('spotter-scale');
} else {
$(this).parent('.dp-spotter-switch').addClass('spotter-scale');
}
});
function showDiv() {
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
(function () {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function () {
localStorage.setItem(storageId, this.checked);
});
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dp-spotter-container">
<div class="dp-top-paragraph">
<p>Some text</p>
<p>Click on the photos once you have spotted, and at the end click on <strong>Get Your Score</strong> to see how you've done</p>
<div id="getScoreLabel" style="display:none; text-align: center;">
<div class="dp-your-score-text" id="getScore">Your Score</div>
<input value="0" readonly="readonly" type="text" id="total" class="dp-scores dp-floating"/>
</div>
</div>
<br/>
<br/>
<!-- Spotter 1 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb1" class="spotter-check" onclick="totalIt()" store="checkbox1">
<span class="dp-spotter-slider"></span>
<span class="dp-spotter-text-label">Item 1- 3 Points</span>
</label>
</div>
<!-- Spotter 2 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb2" class="spotter-check" onclick="totalIt()" store="checkbox2">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 2 - 3 Points</p>
</label>
</div>
<!-- Spotter 3 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="5" id="cb3" class="spotter-check" onclick="totalIt()" store="checkbox3">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">ITem 3 - 5 Points</p>
</label>
</div>
<!-- Spotter 4 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="10" id="cb4ß" class="spotter-check" onclick="totalIt()" store="checkbox4">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 4 - 10 Points</p>
</label>
</div>
Get Your Score
</div>
I'm looking for a way to add to the existing function for the checkboxes if possible.
Unfortunately we can't use local storage in StackOverflow runnable code snippets, so you'll have to head over to my repl.it to see this working in action.
Since you're using jQuery, I've gone ahead and provided a jQuery solution:
Used .attr() to set the checkbox based on local storage
Called totalIt when showing showDiv
If you want to use your existing code, just change box.checked = oldVal === "true" ? true : false; to box.setAttribute('checked', oldVal === "true" ? true : false) and add totalIt to your showDiv function
Demo
https://repl.it/#AnonymousSB/SO53500148
Solution
function showDiv() {
totalIt();
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
function setupBox(box) {
var storageId = box.attr("store");
var oldVal = localStorage.getItem(storageId);
box.attr('checked', oldVal === "true" ? true : false)
box.change(function() {
localStorage.setItem(storageId, this.checked);
});
}
$(document).ready(function () {
$( "input[type='checkbox'][store]" ).each(function( index ) {
setupBox($( this ));
});
})
You can open Chrome Dev Tools, go to Application, and see your local storage

Limit checkbox and calculate between 2 active input fields

I'm trying to calculate the %share which is simply an addition of share1+share2 == 100. However, I want it to work only on the two checked checkboxes.
How do I go about detecting the selected checkbox and apply the function accordingly?
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$("#share1").focusout(function() {
var share1 = $("#share1").val();
var answer = 100 - share1;
$("#share2").val(answer);
});
$("#share2").focusout(function() {
var share2 = $("#share2").val();
var answer = 100 - share2;
$("#share1").val(answer);
});
label {
display: block;
}
.block {
background-color: #eee;
padding: 15px;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<h6>You can choose a maximum of 2 users</h6>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share1" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share2" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share3" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share4" class="form-control" placeholder="% share" required>
</div>
</div>
Do you have a specific reason to use focusout?
You could catch the ID's of the two "selected" elements inside your checkbox function. Or to be precise, get id of input that is in the next div inside the clicked checkbox's parent:
var active1, active2;
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
let checked = $('input.addnominee:checked');
active1 = $(checked[0]).parent().next('div').children('input').attr('id');
//Let's assign active2 only if we have multiple selected checkboxes:
if(checked.length > 1) active2 = $(checked[1]).parent().next('div').children('input').attr('id');
});
Here's example with click. To simplify it a bit, I added stepper class into every number input, and we're now detecting click for the class stepper:
$(document).on('click','.stepper',function(){
if($(this).attr('id') == active1){ //Check which one user clicked
if(active2 != undefined){ //Make the math only if we have another active element
var share1 = $('#'+active1).val();
var answer = 100 - share1;
$('#'+active2).val(answer);
}
}else if($(this).attr('id') == active2){
if(active1 != undefined){
var share2 = $('#'+active2).val();
var answer = 100 - share2;
$('#'+active1).val(answer);
}
}
});
Fiddle: https://jsfiddle.net/xpvt214o/677733/
This surely works also with focusout, but you need to remember that clicking stepper wont focus the input, so it wouldn't be very functional.
And with this same idea you could also disable the inputs which are not 'active'.
I hope this helps!
EDIT:
Maybe a bit simplified version with the same idea:
jQuery(document).ready(function($) {
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$(document).on('click','.stepper',function(){
var checked = $('input.addnominee:checked');
if(checked.length > 1){
var active1 = $(checked[0]).parent().next('div').children('input');
var active2 = $(checked[1]).parent().next('div').children('input');
var share = $(this).val();
var answer = 100 - share;
if($(this).attr('id') == $(active1).attr('id')){
$(active2).val(answer);
}else if($(this).attr('id') == $(active2).attr('id')){
$(active1).val(answer);
}
}
});
});
Fiddle: https://jsfiddle.net/128uzmj3/

Issues with if-statement adding players with `is-inactive` class to input

Problem
The maximum number of players for each position is:
2 out of 4 goalies
6 out of 15 defencemen
12 out of 31 forwards
I've gotten to the point where I'll click on a hockey player and that name gets added to a input field in a form, but if you already have two goalies selected, ie has a class of is-active and then click on one of the other two unselected players with the default is-inactive class, that name will still be added into an input when there should only be two goalies max. And unfortunately, this is also the case with the defencemen and the forwards too.
Goal
When starredGoaltenders === maxGoaltenders or starredDefencemen === maxDefencemen or starredForwards === maxFowards the names of players that do not have not been selected of that specific position and do not have an is-active class should not be added to any input in the form.
scripts.js
function countSelected() {
$(".player").on("click", function(){
// Checks if the maximum number of players have been selected
// If so, return false and then do nothing
// If not, the class will toggle from `is-inactive` to `is-active`
if ($(this).find(".picked.is-inactive.full").length > 0) return false;
$(this).find(".picked").toggleClass("is-inactive is-active");
$(".player").removeClass("not-picked");
$(".player").not(":has(.is-active)").addClass("not-picked");
// Count the number of players with stars
var starredGoaltenders = $(".player--goalie").find(".picked.is-active").length;
var starredDefencemen = $(".player--defencemen").find(".picked.is-active").length;
var starredForwards = $(".player--forward").find(".picked.is-active").length;
console.log(starredGoaltenders, starredDefencemen, starredForwards);
// The number of starred players for each position cannot exceed the following numbers
var maxGoaltenders = 2;
var maxDefencemen = 6;
var maxFowards = 12;
// If the number of starred players hits its max, a class of `is-completed` is adding to the corresponding checkmark to indicate that the task has been completed
if (starredGoaltenders === maxGoaltenders) {
$(".checkmark--goalie").addClass("is-completed");
$(".player--goalie").find(".picked").addClass("full");
} else {
$(".checkmark--goalie").removeClass("is-completed");
$(".player--goalie").find(".picked.is-inactive").removeClass('full');
}
if (starredDefencemen === maxDefencemen) {
$(".checkmark--defencemen").addClass("is-completed");
$(".player--defencemen").find(".picked").addClass("full");
} else {
$(".checkmark--defencemen").removeClass("is-completed");
$(".player--defencemen").find(".picked.is-inactive").removeClass('full');
}
if (starredForwards === maxFowards) {
$(".checkmark--forward").addClass("is-completed");
$(".player--forward").find(".picked").addClass("full");
} else {
$(".checkmark--forward").removeClass("is-completed");
$(".player--forward").find(".picked.is-inactive").removeClass('full');
}
// If all the conditions are met show the submit vote button
if (starredGoaltenders === maxGoaltenders && starredDefencemen === maxDefencemen && starredForwards === maxFowards) {
$(".btn--submit").show();
$(".btn--submit").addClass("slideLeft");
} else{
$(".btn--submit").hide();
$(".btn--submit").removeClass("slideLeft");
}
});
} countSelected();
// Every time a player is clicked, note the name of the player
$(".player").on("click", function(){
var playerNames = [];
$("input:text").each(function(i, t) { playerNames.push(t.value) });
if ($(this).find("picked.is-active")) {
var playerName = $(this).find(".player__name").html();
var index = playerNames.indexOf(playerName);
if (index == -1) // Add player
$("input:text:eq(" + playerNames.indexOf("") + ")").val(playerName);
else // Remove player
$("input:text:eq(" + index + ")").val("");
} else {
$("input").val("");
}
});
index.html - Snippet includes form and one out of the 60 available players to be clicked on
<form id="form">
<input type="text" name="p1" id="p1">
<input type="text" name="p2" id="p2">
<input type="text" name="p3" id="p3">
<input type="text" name="p4" id="p4">
<input type="text" name="p5" id="p5">
<input type="text" name="p6" id="p6">
<input type="text" name="p7" id="p7">
<input type="text" name="p8" id="p8">
<input type="text" name="p9" id="p9">
<input type="text" name="p10" id="p10">
<input type="text" name="p11" id="p11">
<input type="text" name="p12" id="p12">
<input type="text" name="p13" id="p13">
<input type="text" name="p14" id="p14">
<input type="text" name="p15" id="p15">
<input type="text" name="p16" id="p16">
<input type="text" name="p17" id="p17">
<input type="text" name="p18" id="p18">
<input type="text" name="p19" id="p19">
<input type="text" name="p20" id="p20">
<button class="btn btn--submit" type="submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>
</form>
<div class="player player--forward year--2000 year--2010">
<div class="tooltip">
<p class="tooltip__name">Mark Stone</p>
<p class="tooltip__hometown"><span>Hometown:</span> Winnipeg, Man.</p>
<p class="tooltip__years"><span>Years Played:</span> 2008-2012</p>
<div class="tooltip__stats--inline">
<div class="stats__group stats--games">
<p class="stats__header">GP</p>
<p class="stats__number stats__number--games">232</p>
</div>
<div class="stats__group stats--goals">
<p class="stats__header">G</p>
<p class="stats__number stats__number--goals">106</p>
</div>
<div class="stats__group stats--assists">
<p class="stats__header">A</p>
<p class="stats__number stats__number--assists">190</p>
</div>
<div class="stats__group stats--points">
<p class="stats__header">Pts</p>
<p class="stats__number stats__number--points">296</p>
</div>
<div class="stats__group stats--penalties">
<p class="stats__header">Pim</p>
<p class="stats__number stats__number--penalties">102</p>
</div>
</div>
</div>
<div class="player__headshot player--mstone">
<div class="picked is-inactive"><i class="fa fa-star" aria-hidden="true"></i></div>
</div>
<p class="player__name">Mark Stone</p>
<p class="player__position">Forward</p>
</div>
Probably, the easiest way to approach this problem is to repopulate all your inputs every time someone clicks on a player, rather than trying to populate each input once. This means you can keep your application state in a simple, easily understood data structure that is independent of your DOM/UI, rather than having to consult the DOM each time something new happens.
This is how I would probably write it.
var players = [
{name: 'Ovechkin', type: 'F'},
{name: 'Dubnyk', type: 'G'}
// your complete player list goes here
],
selectedPlayers: []; // these are the players the user has chosen
var getCurrentPlayerCount = function (playerType) {
// return the number of players currently selected of one type
return selectedPlayers.reduce(function (count, player) {
if (player.type === playerType) return count + 1;
return count;
}, 0);
}
var selectPlayer = function (player) {
// You call this when someone clicks on a player
var currentForwardCount = getCurrentPlayerCount('F')
currentDefenceCount = getCurrentPlayerCount('D'),
currentGoalieCount = getCurrentPlayerCount('G');
// Do nothing (or show a UI message) if someone goes over their
// player-type limit
if (player.type === 'F' && currentForwardCount > 12) return;
if (player.type === 'D' && currentDefenceCount > 6) return;
if (player.type === 'G' && currentGoalieCount > 2) return;
// If you get here, it means the player can be added, so add
// it to the user's list
selectedPlayers.push(player);
updateUI();
}
I'm not including updateUI here. You can work that out on your own.
If you need to support IE 8 or any other browser that does not support Array.prototype.reduce, you will need to do getCurrentPlayerCount differently.

Setting rules on a form

So, I need a function to check if the rules I've made apply to the options I have in my form.
The first box is a name box and it needs to have at least three letters and contain at least one whitespace to pass.
The other box is age, it needs to have a number between 1 and 125, I can do that on my own but I'm thinking there might be a nice way to set all of the rules at once so I thought I'd include it.
The third option is a set of three radio buttons of which one has to be selected and the fourth box is an info box that should consist of a text with at least 30 letters. These rules should be checked on the press of a button, this is how far I've gotten on my own:
var sendButton = $("button:first").addClass("sendButton");
var age = document.getElementsByName('age')[0].value;
sendButton.click(function(){
var infoName = document.getElementsByName('infoName')[0].value;
if (infoName.length<3){
console.log("Your name must consist of at least three letters and contain a whitespace");
};
}
});
<section class="column">
<h2>Contact us</h2>
<form action="#">
<fieldset>
<legend>Form</legend>
<div class="textinput">
<label for="infoName">Ditt namn:</label>
<input type="text" name="infoName" placeholder="ex. John Doe">
</div>
<div class="textinput">
<label for="infoName">Din ålder:</label>
<input type="text" name="age" placeholder="ex. 25">
</div>
<div class="radioSelection">
<label>Choose your favorite</label>
<input type="radio" name="favorite" id="html" value="html">
<label for="html">HTML</label>
<input type="radio" name="favorite" id="js" value="js">
<label for="js">JavaScript</label>
<input type="radio" name="favorite" id="css" value="css">
<label for="css">CSS</label>
</div>
<div class="textareainput">
<label for="info">Info about you:</label>
<textarea placeholder="Type something about yourself, this area must contain 30 letters or more"></textarea>
</div>
<div class="action">
<button>Send</button>
</div>
function validateForm(){
var infoName = document.getElementsByName('infoName')[0].value;
var age= document.getElementsByName('age')[0].value;
var favourites = document.getElementsByName('favorite');
var problems = 0;
if(infoName.length < 3){
// Failed length validation
problems++;
}
var spaceIndex = infoName.indexOf(' ');
if(spaceIndex === -1){
// Name does not contain a space.
problems++;
}
else if(spaceIndex === 0){
// Name begins with space
problems++;
}
else if(spaceIndex === infoName.length - 1){
// Space is last character.
problems++;
}
var hasCheck = false;
for(var i = 0; i < favourites.length; i++){
if(favourites[i].checked){
hasCheck = true;
break;
}
}
if(!hasCheck){
// No radio button has been checked.
problems++;
}
var ageNum = parseInt(age);
if(isNaN(ageNum)) {
// Age is not a number
problems++;
}
else if(ageNum < 1 || ageNum > 125){
// Age is not within boundaries
problems++;
}
/// etc etc, for all your validations.
return problems === 0;
}
At the end of the validation, if any problems are detected, the form will not be submitted (because problems === 0 is false). Also the number validation I've put in there is not very robust. Check out this question which goes into detail about number validation.
The validation method should be called on submission of the form, rather than when the button is clicked
$('form').submit(function(e){
var valid = validateForm();
if(!valid){
e.preventDefault();
return false;
}
});

Categories