Tricky Javascript logic with Objects, Array and Booleans - javascript

I am having a lot of issue trying to figure out this logic. Let me set the stage here:
In the HTML there are some form/input elements type radio. Each of them have an ID assigned to it.
<form>
<input type="radio" name="oneAllowed" id="yesterday" />
<input type="radio" name="oneAllowed" id="today" />
<input type="radio" name="oneAllowed" id="tomorrow" />
</form>
Using Javascript essentially what I am trying to do is loop through the 3 objects, since they all have same name assigned within HTML only a single one can be selected, whichever one is returning true I want grab hold of that result then access the second key:value pair, for example for 'commitYesterday' it would be 'commitYesterday.hasValue();' and dispatch that to a different function for other calculation.
var urgentOrderSelector = function(){
var commitYesterday = {
isChecked: document.getElementById("yesterday").checked,
hasValue: function(){
if (this.isChecked == true) {
return 3;
};
};
};
var commitToday = {
isChecked: document.getElementById("today").checked,
hasValue: function(){
if (this.isChecked == true) {
return 2;
};
};
};
var commitTomorrow = {
isChecked: document.getElementById("tomorrow").checked,
hasValue: function(){
if (this.isChecked == true) {
return 1;
};
};
};
var urgentArray = [commitYesterday.isChecked, commitToday.isChecked, commitTomorrow.isChecked];
for(var i = 0; i <= urgentArray.length-1; i++){
if (urgentArray[i].isChecked == true) {
//This is where I am stuck. I was thinking of doing perhaps the following:
return urgentArray[i].hasValue();
};
}
};

Why don't you change your HTML to this:
<form>
<input type="radio" name="oneAllowed" id="yesterday" value="3" />
<input type="radio" name="oneAllowed" id="today" value="2" />
<input type="radio" name="oneAllowed" id="tomorrow" value="1" />
</form>
And use document.querySelector to get the selected elements:
document.querySelector('[type="radio"][name="oneAllowed"]:checked').value
If you actually need to run specific functions dependend on which radio box is checked you could add an attribute data-fn="fnName" to each input and then create an object with the keys as functions:
var fns = {'fnName1': function () {}, 'fnName2': function() {} …};
And then call the function defined by the Attribute:
fns[document.querySelector('[type="radio"][name="oneAllowed"]:checked').getAttribute('data-fn')]();

Not exactly sure what your end goal is.
But here's a more minified version of your logic. Hope it helps.
var urgentOrderSelector = function(){
var radioDict = {'yesterday':3, 'today':2, 'tomorrow':1};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')];
};
Alternatively, if you wanted to execute some function based on the selection, you could store the function pointers and execute them accordingly, ie:
var funcYesterday = function(){alert('yesterday');};
var funcToday = function(){alert('today');};
var funcTomorrow = function(){alert('tomorrow');};
var funcUrgentOrder = function(){
var radioDict = {
'yesterday' : funcYesterday,
'today' : funcToday,
'tomorrow' : funcTomorrow
};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')]();
};
Or, much simpler, since you are using the 'value' property on your radios:
function urgentOrderSelector = function() {
return $('input[name=oneAllowed]:checked').val();
};

Related

Store multiple checkbox inputs in local storage

I have multiple checkbox inputs that look like this:
<input type="checkbox" id="box-1">
<input type="checkbox" id="box-2">
<input type="checkbox" id="box-3">
I want to store their values (checked or unchecked) in the browser's local store.
The javascript that I'm using to do this is:
function onClickBox() {
let checked = $("#box-1").is(":checked");
let checked = $("#box-2").is(":checked");
let checked = $("#box-3").is(":checked");
localStorage.setItem("checked", checked);
}
function onReady() {
let checked = "true" == localStorage.getItem("checked");
$("#box-1").prop('checked', checked);
$("#box-2").prop('checked', checked);
$("#box-3").prop('checked', checked);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
The first part saves the checkbox's state on the click and the second part loads it when the page refreshes.
This works well if the lines for box 2 and 3 are removed, but I need it to work with all the checkboxes.
Your main issue here is that you're only storing a single value in localStorage, checked, which will be overwritten every time you check a different box. You instead need to store the state of all boxes. An array is ideal for this, however localStorage can only hold strings, so you will need to serialise/deserialise the data when you attempt to read or save it.
You can also simplify the logic which retrieves the values of the boxes by putting a common class on them and using map() to build the aforementioned array. Try this:
<input type="checkbox" id="box-1" class="box" />
<input type="checkbox" id="box-2" class="box" />
<input type="checkbox" id="box-3" class="box" />
jQuery($ => {
var arr = JSON.parse(localStorage.getItem('checked')) || [];
arr.forEach((c, i) => $('.box').eq(i).prop('checked', c));
$(".box").click(() => {
var arr = $('.box').map((i, el) => el.checked).get();
localStorage.setItem("checked", JSON.stringify(arr));
});
});
Working example
function onClickBox() {
let checked1 = $("#box-1").is(":checked");
let checked2 = $("#box-2").is(":checked");
let checked3 = $("#box-3").is(":checked");
localStorage.setItem("checked1", checked1);
localStorage.setItem("checked2", checked2);
localStorage.setItem("checked3", checked3);
}
function onReady() {
let checked1 = "true" == localStorage.getItem("checked1");
let checked2 = "true" == localStorage.getItem("checked2");
let checked3 = "true" == localStorage.getItem("checked3");
$("#box-1").prop('checked', checked1);
$("#box-2").prop('checked', checked2);
$("#box-3").prop('checked', checked3);
$("#box-1").click(onClickBox);
$("#box-2").click(onClickBox);
$("#box-3").click(onClickBox);
}
$(document).ready(onReady);
Of course you could simplify it further by doing
function onClickBox(boxNumber) {
let checked = $("#box-" + boxNumber).is(":checked");
localStorage.setItem("checked" + boxNumber, checked);
}
function onReady() {
[1, 2, 3].forEach( function(boxNumber) {
$("#box-" + boxNumber).prop(
'checked',
localStorage.getItem("checked" + boxNumber)
);
$("#box-" + boxNumber).click( function() {
localStorage.setItem(
"checked" + boxNumber,
$("#box-" + boxNumber).is(":checked")
);
});
})
}
$(document).ready(onReady);
Your check variable is getting overwritten, you can put it inside for loop.
So your code becomes,
function onClickBox() {
for(var i=1;i<=3;i++){
let checked=$("#box-"+i).is(":checked");
localStorage.setItem("checked-"+i, checked);
}
}
function onReady() {
for(var i=1;i<=3;i++){
if(localStorage.getItem("checked-"+i)=="true"){
var checked=true;
}
else{
var checked=false;
}
$("#box-"+i).prop('checked', checked);
onClickBox();
}
}
$(document).ready(onReady);
Please follow the below Code (Very Simple Javascript works)
<input type="checkbox" id="box">checkbox</input>
<button type="button" onClick="save()">save</button>
<script>
function save() {
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked;
</script>
with simple modification, you can use it without save button..
Hope this Helps you..

I want to increase a value when some checkboxes are checked

I want to increase the price if one or more check boxes are checked. Here is the code i have but it does not work
HTML
<input type="checkbox" value="15" />Checkbox
<br/>
<br/>
<span id="result"></span>
JAVASCRIPT
var a=0;
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
var a = a+value;
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
check();
}
You've scoped your a variable away in the check function, and you're calling the function check without the proper "this".
This should work
var a = 0;
window.onload = function() {
var input = document.querySelector('input[type=checkbox]');
function check() {
a = a + parseInt(this.value, 10);
document.getElementById('result').innerHTML = 'result ' + a;
}
input.onchange = check;
input.onchange();
}
your variable "a" is in global scope when you have initialized it on the top var a = 0; If you want to use it, you can directly do a = a + 1.
When you declare it again as a var inside check function, it is now a new variable "a" bound to the check function scope as a new variable and its not referring to the variable declared at the top.
So the solution is remove declaration var and directly use it as a = a + 1 inside check function.
Also you need to check if checkbox is checked :
here is a working fiddle : https://jsfiddle.net/1m09z0cg/
There are a couple of things wrong.
First, querySelector will only return the first element that matches the selector, if you want to get all checkboxes you'll have to use querySelectorAll.
Second, you're using var a = a+value; if you want to add value to the previous value of the global variable a you should use a = a+value;, by using var a = ... you're declaring a new variable a in the current context.
Third, there is no variable value, if you're trying to get the value of the clicked element use event.currentTarget.value.
var checkboxes = Array.from(document.querySelectorAll("input[type='checkbox']"));
var result = document.querySelector("#result");
checkboxes.forEach(function(checkbox){
checkbox.onchange = function(){
var total = checkboxes.reduce(function(a, c){
return a + (c.checked ? parseInt(c.value):0);
}, 0);
result.textContent = "Result " + total;
}
});
<input type="checkbox" value="15" />Checkbox
<br/>
<input type="checkbox" value="15" />Checkbox 2
<br/>
<input type="checkbox" value="15" />Checkbox 3
<br/>
<br/>
<span id="result">Result 0</span>

i have code it can be sum two textbox values using javascript

i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again?
<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}
</script>
<input class="input_field2" type="text" readonly name="advance"
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">
You could keep a property on the read-only text field to keep the old value:
function B()
{
var adv = document.getElementById('advance'),
rec = document.getElementById('recamt');
if (typeof adv.oldvalue === 'undefined') {
adv.oldvalue = parseFloat(adv.value); // keep old value
}
adv.value = adv.oldvalue + parseFloat(rec.value));
rec.value = '';
return false;
}
You're calling the sum function every time the readonly input is focused using the new value. If you only want it to add to the original value, you need to store it somewhere.
HTML:
<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">
JS:
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onclick = function() {
this.value = parseFloat(originalValue) +
parseFloat(document.getElementById('recamt').value);
return false;
};
http://jsfiddle.net/hQbhq/
Notes:
You should bind your handlers in javascript, not HTML.
The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox.

How To copy object by value using jquery

Hello I'm having an issue with this check box :
<input type="checkbox" id="hideTempSeries" checked="checked" value="0" />
Temperature <br />
<input type="checkbox" id="hideFlowSeries" checked="checked" value="1" />
Flow <br />
<input type="checkbox" id="hidePressSeries" checked="checked" value="2"/>
Pressure <br />
<input type="checkbox" id="hideCondSeries" checked="checked" value="3" />
Conductivity <br />
.. and this jQuery function that sends an array of this check box values to a function called
removePanes(checkedArray) " every time any of the check boxes have changed "
$("#tools :checkbox").change(function(){
if($(this).prop('checked')){// when Checked
}
else{// when unChecked
var checkedArray = [] ;
$("#tools :checkbox").each(function(index,value){
if($(this).prop('checked') == false){checkedArray.push($(this).val())}
});
removePanes(checkedArray) ;
}
removePanes() function
function removePanes(id){
var removeUncheckedSeries = $.map(newSeries , function(index,value){
for(var i=0 ; i < id.length ; i++){
if(index.yAxis == id[i])return null;
}
return index ;
});
var modified = $.map(removeUncheckedSeries, function(index,value) {
index.yAxis = 15 ;
return index ;
});
console.log(modified) ;
} ;
this is newSeries[] Object
The removePanes(checkedArray) function then takes this array and removes all the objects equivalent to the unchecked values from : newSeries[] object
Then it sets all the yAxis values equal to 15.
This function is not working.
Because each time the check box changed the function doesn't reload the newSeries[] object it just modifies it on the last change.
What it does is, the first click works fine and then it set all the yAxis to 15. When I unchecked any other boxes since all the yAxis equal to 15 and the jQuery array send value from 0 to 3 nothing happened.
QUESTION: How can i make the removePanes(checkedArray) reload with the newSeries[] object each time a change on check box trigger?
That is happening because objects are by default copied by reference
in Javascript.
So if you change any property of copied object from anywhere it will affect all others. To copy an object by value only(or clone) you can use jQuery's $.extend() method like Jonh Resig(Yes he himself) showed here https://stackoverflow.com/a/122704/344304
var newObj = $.extend(true, {}, oldObj); // deep copy
So change your removePanes function like following
function removePanes(id) {
var seriesCopy = jQuery.extend(true, {}, newSeries);
var removeUncheckedSeries = $.map(seriesCopy, function(obj, index) {
return $.inArray(obj.yAxis,id) == -1 ? obj : null;
});
var modified = $.map(removeUncheckedSeries, function(obj, index) {
obj.yAxis = 15;
return obj;
});
console.log(modified);
};​
Demo: http://jsfiddle.net/joycse06/w2KS2/

Select all radio buttons which are checked with prototype

I have several input elements which look like this:
<input type="radio" checked="checked" value="1" name="handle[123]" />
<input type="radio" checked="checked" value="2" name="handle[456]" />
The number inside the name attribute is an object id i need. Now what I want to do is:
Fetch all input which are of type="radio" and are checked with prototype
Put all ids and values in an associative array
...so the resulting array looks something like this:
array{ 1 => 123, 2 => 456 }
Any ideas?
Here's what I came up with:
var results = [];
document.body.select('input[type=radio]:checked').each(function (element) {
var object = {};
object[element.value] = element.name.match(/\d+/)[0];
results.push(object);
});
new Ajax.Request('/some_url', {
method: 'post',
parameters: results
});
Demo
To get the checked radio button given a form id, and the name of the radio group:
function RF(el, radioGroup) {
if($(el).type && $(el).type.toLowerCase() == 'radio') {
var radioGroup = $(el).name;
var el = $(el).form;
} else if ($(el).tagName.toLowerCase() != 'form') {
return false;
}
var checked = $(el).getInputs('radio', radioGroup).find(
function(re) {return re.checked;}
);
return (checked) ? $F(checked) : null;
}
var value = RF('form_id', 'radio_grp_name');
Hope it helps
$$('input:checked[type=radio]').each(function (ele) {
output[ele.name.match(/\d+/)[0]] = ele.value;
});
This would give the desired output using prototype

Categories

Resources