Adding multiple elements by name to a JSON object using Javascript - javascript

I have a function that takes in, for example, 10 textboxes worth of values and puts them into a JSON string that I then store in a cookie. I have no issues if I hard code the problem where I'm grabbing the element "assignment[]", but I'd also like to add other text box values to it, say "quizzes[]", as an example, in order to have one long string that I would then convert to a JSON string.
function setObject(name, score)
{
this.name = name;
this.score = score;
}
function setCookie()
{
var cookieName = "assignments";
var cookieValue = document.getElementsByName("assignments[]");
var arr = [];
for(var i=0;i<cookieValue.length;i++)
{
var setObj = new setObject(cookieName + i, cookieValue[i].value);
arr.push(setObj);
}
document.cookie = JSON.stringify(arr);
}
This code above works just fine for just the "name[]" textboxes, but I'd like to be able to add other elements to that same JSON string.
My current output would look like this:
[{"name":"assignments0","score":"1"},{"name":"assignments1","score":"2"},
{"name":"assignments2","score":"3"},{"name":"assignments3","score":"4"}]
My expected output would look like this if I were able to add different textbox arrays through my function:
[{"name":"assignments0","score":"22"},{"name":"assignments1","score":"19"},
{"name":"assignments2","score":"9"},{"name":"assignments3","score":"20"},
{"name":"quizzes0","score":"5"},{"name":"quizzes1","score":"9"}]
Any help in the right direction would be much appreciated.

You can use querySelectorAll() with attribute selector to fetch all the elements like
function setObject(name, score) {
this.name = name;
this.score = score;
}
function setCookie() {
var els = document.querySelectorAll('input[name="assignments[]"],input[name="quizes[]"]');
var arr = [];
for (var i = 0; i < els.length; i++) {
var setObj = new setObject(els[i].name.slice(0, -2) + i, els[i].value);
arr.push(setObj);
}
result1.innerHTML = JSON.stringify(arr, null, 2);
var arr = [].map.call(els, function(el) {
return new setObject(el.name.slice(0, -2) + i, el.value);
});
result2.innerHTML = JSON.stringify(arr, null, 2);
}
setCookie();
<input name="assignments[]" value="1" />
<input name="assignments[]" value="2" />
<input name="assignments[]" value="3" />
<input name="assignments[]" value="4" />
<input name="quizes[]" value="1" />
<input name="quizes[]" value="2" />
<input name="quizes[]" value="3" />
<input name="quizes[]" value="4" />
<pre id="result1"></pre>
<pre id="result2"></pre>

You can assign all the Input Name Arrays to an Array and iterate over it, as in the code below.
var inputs = ["assignments", "quizzes", "three", "four"];
function setObject(name, score) {
this.name = name;
this.score = score;
}
function setCookie() {
var inputs = ["assignments", "quizzes", "three", "four"];
var arr = [];
for (var i = 0; i < inputs.length; i++) {
var cookieName = inputs[i];
var cookieValue = document.getElementsByName(inputs[i] + '[]');
for (var j = 0; j < cookieValue.length; j++) {
var setObj = new setObject(cookieName + j, cookieValue[j].value);
arr.push(setObj);
}
}
result.innerHTML = JSON.stringify(arr, null, 2);
//document.cookie = JSON.stringify(arr);
}
setCookie();
<input name="assignments[]" value="1" />
<input name="assignments[]" value="2" />
<input name="assignments[]" value="3" />
<input name="quizzes[]" value="11" />
<input name="quizzes[]" value="22" />
<input name="quizzes[]" value="33" />
<input name="three[]" value="111" />
<input name="three[]" value="222" />
<input name="three[]" value="333" />
<input name="four[]" value="1111" />
<input name="four[]" value="2222" />
<input name="four[]" value="3333" />
<pre id="result"></pre>
OUTPUT
[
{"name": "assignments0","score": "1"},
{"name": "assignments1","score": "2"},
{"name": "assignments2","score": "3"},
{"name": "quizzes0","score": "11"},
{"name": "quizzes1","score": "22"},
{"name": "quizzes2","score": "33"},
{"name": "three0","score": "111"},
{"name": "three1","score": "222"},
{"name": "three2","score": "333"},
{"name": "four0","score": "1111"},
{"name": "four1","score": "2222"},
{"name": "four2","score": "3333"}
]

Just make it a function?
function getElementsArr(elementsName) {
var elements = document.getElementsByName(elementsName + "[]");
var arr = [];
for(var i=0; i < elements.length;i++)
{
var setObj = new setObject(elementsName + i, elementss[i].value);
arr.push(setObj);
}
return arr;
}
function setCookie(elementNames)
{
var allElements = [];
for(var i = 0; i < elementNames.length; i++) {
allElements.push(getElementsArr(elementNames[i]));
}
document.cookie = JSON.stringify(allElements);
}
setCookie(['assignments', 'quizzes']);

Related

How to format jQuery .map() with keys and values?

I try to create array with keys and values by using the jQuery .map().
When I use my code I have a problem with formatting:
["name1:1", "name2:1", "name3:0"]
I need:
['name1':1,'name2':1,'name3':0]
I spend a few hours to make it work, but I don't know what is wrong.
HTML
<div class="inputs-container">
<input id="name1" name="name1" type="checkbox" class="multicheckbox-item" value="1" checked="checked">
<input id="name2" name="name2" type="checkbox" class="multicheckbox-item" value="1" checked="checked">
<input id="name3" name="name3" type="checkbox" class="multicheckbox-item" value="0">
</div>
JS
var inputsContainer = $('.inputs-container');
var inputValues = inputsContainer.find( 'input.multicheckbox-item' ).map( function() {
var name = $(this).attr('name');
var active = 0;
if( $(this).prop( 'checked' ) ){
var active = 1;
}
return name + ':' + active;
}).get();
console.log( inputValues );
You'll want an object and .each (or .forEach in native array terms).
var inputsContainer = $('.inputs-container');
var inputValues = {};
var inputValues = inputsContainer.find('input.multicheckbox-item').each( function() {
inputValues[$(this).attr('name')] = ($(this).prop('checked') ? 1 : 0);
});
console.log(inputValues);
Try This
var inputsContainer = $('.inputs-container');
var inputValues_key = inputsContainer.find( 'input.multicheckbox-item' ).map(function() {
var name = $(this).attr('name');
return name;
}).get();
var inputValues_value = inputsContainer.find( 'input.multicheckbox-item' ).map(function() {
var active = $(this).prop('checked')? 1 : 0;
return active;
}).get();
var inputValues = [], length = Math.min(inputValues_key.length, inputValues_value.length);
for(var i = 0; i < length; i++) {
inputValues.push([inputValues_key[i], inputValues_value[i]]);
}
console.log( inputValues );

How to retrieve session storage values and pass it to radio buttons and checkboxes?

As the question is asking, can you get the values from the session storage or local storage to radio buttons on html and the same thing for the checkboxes?
My code:
var customername = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var curcustomer1 = {"firstname" : getCookie("firstname"), "lastname" : getCookie("lastname")};
var lastvist = {"date" : dateall} // only display the date and time
var myJSON = JSON.stringify(customername);
var myJSON1 = JSON.stringify(lastvist); // has the date when the user last has visited
var myJSON2 = JSON.stringify(curcustomer1);
var myJSON3full = JSON.stringify(custinfo);
sessionStorage.setItem("custinfo", myJSON3full);
var objectfull = sessionStorage.getItem("custinfo");
objfull = JSON.parse(objectfull);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
if(object != myJSON) {
sessionStorage.setItem("customername", myJSON);
var object = sessionStorage.getItem("customername");
obj = JSON.parse(object);
var curcustomer = customername;
var myJSONcopy = JSON.stringify(curcustomer);
var object2 = sessionStorage.setItem("curcustomer", myJSONcopy);
var msg5 = "Welcome ";
document.getElementById("customer").innerHTML = msg5 + " " + "New Customer";
document.getElementById("date1").innerHTML = "";
var radiobtn = document.getElementsByName("type");
if(radiobtn.value != 8) {
document.elem.type.value="8";
}
var radiobtn1 = document.getElementsByName("special");
if(radiobtn1.value != 0) {
document.elem.special.value="0";
}
for (var i = 0; i < extras.length; i++) {
if (extras[i].checked) {
extras[i].checked = false;
}
}
}
if(object == myJSONcopy) {
radiobtn = document.getElementsByClassName("type").innerHTML = sessionStorage.getItem("type");
radiobtn1 = document.getElementsByClassName("special").innerHTML = sessionStorage.getItem("special");
checboxes = document.getElementsByClassName("extras").innerHTML = sessionStorage.getItem("extras");
}
<td>
<input type="radio" name="type" value="8" checked>Small $8.00
<br>
<input type="radio" name="type" value="10">Medium $10.00
<br>
<input type="radio" name="type" value="15">Large $15.00
<br>
<input type="radio" name="type" value="18">Extra Large $18.00
<br>
<br>
</td>
if you are trying to add the item to multiple buttons that share the same className then you will have to do something like this:
var list = document.getElementsByClassName('type');
var i;
for (i = 0; n < list.length; ++i) {
list[i].value= sessionStorage.getItem('events')
};
But if it's just one button then I will suggest you use getElementById
like this
document.getElementById('Id').value = sessionStorage("events");

Get the element name attribute in JavaScript

How can I get the element name attribute in JavaScript?
HTML :
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input type="submit"></input>
JavaScript :
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var elname = document.getElementByClassName('.so')[i].getAttribute('name');
//var eln = document.getElementsByTagName("input")[i].getAttribute("name");
var vala = document.querySelectorAll('.so')[i].value;
//alert(vala);
alert(elname);
}
After I run the script I want the person object to be set with this data:
person {
Name: "bob",
LastName: "Feyzi",
Email: "",
Adderss: ""
}
JSFiddle
Use the collection that you've already found with querySelectorAll to get the values of the value and name attributes :
var person = {}
var cars = document.querySelectorAll(".so")
for (i = 0; i < cars.length; i++) {
person[cars[i].name] = cars[i].value
}
console.log(person)
JSFiddle
Because getElementByClassName does not exist (also it would have no use in your script). Use this:
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
alert(cars[i].name)
}
Firstly, use cars variable instead of calling querySelectorAll every time.
Secondly, use addEventListener to execute code on click.
Fiddle: http://jsfiddle.net/guyavunf/3/
Code:
// HTML
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input class="submit" type="submit"></input>
// JS
document.querySelector('.submit').addEventListener('click', function() {
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var name = cars[i].name;
var value = cars[i].value;
alert(name + ': ' + value);
}
});

Convert a string into a character array using JavaScript

Continue on my Javascript - Radio Button onChange
Here is my code:
<html>
<head>
<script type="text/javascript">
function Change(radio)
{
for(i = 1; i <=3; i++)
{
if(i == radio.value)
{
setvalue = "Y";
value = setvalue;
radiovalue = radio.value;
}
else
{
setvalue = "N";
value = setvalue;
radiovalue = radio.value;
}
ChangeValue(setvalue,value);
}
function ChangeValue(setvalue,value)
{
var getvalue = value;
document.write(getvalue);
}
}
</script>
</head>
<body>
<?php
for($i = 1; $i <= 3; $i++)
{
?>
<input type="radio" name="choice" value="<?php echo $i;?>" onchange="Change(this)" /><br />
<?php
}
?>
</body>
</html>
From the above code, if I clicked the first radio button, the output is YNN.
Now I want to separate the value with commas (YNN) and put the result into an array ("Y","N","N").
I wrote the following inside ChangeValue function:
function ChangeValue(setvalue, value)
{
var getvalue = value;
document.write(getvalue);
var seperate = new array();
seperate = getvalue.spilt(",");
}
However the above code doesn't put my value into array.
What am I doing wrong? Any solutions to solve this problem?
You have to split the string into separate chars as array.
var str = 'YNN'; //or whatever
var strWithComma = str.split(''); //to char array
After this you can join the chars to a new string for display output.
var str = 'YNN';
var strWithComma = str.split('').join(','); //'YNN' (string) --> ['Y','N','N'] (string/char array) --> "Y,N,N" (string)
Hope this helps
Demo
The JavaScript String object has a split method which does what you're requesting. It partitions the string based on a specified delimiter, and returns an array with each partition at its own index. If you split with a blank (empty string) delimiter, you tokenize the string into individual characters.
To get the values of your radio buttons as a string, you can iterate through them and examine the value property of each one.
var input = "YNN"
var result = input.split(''); // returns ["Y", "N", "N"]
var valStr = "";
function main() {
var radioBtns = document.getElementsByName("choice");
for (var i = 0; i < radioBtns.length; i++) {
radioBtns[i].onchange = valChange;
}
valStr = Array(radioBtns.length + 1).join("N")
}
function valChange(event) {
var changedElem = event.target;
var elemValue = changedElem.value;
var elemIdx = +elemValue - 1;
var resultStr = replaceChar(valStr, elemIdx, 'Y');
getElem("outputStr").innerHTML = resultStr;
getElem("outputArr").innerHTML = resultStr.split('');
}
function replaceChar(str, idx, chr) {
return str.substr(0, idx) + chr + str.substr(idx + chr.length);
}
function getElem(id) {
return document.getElementById(id);
}
window.onload = main;
span[id^="output"] {
border: 2px solid black;
margin: 2px;
width: 50px;
}
div {
margin-top: 7px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Select an option:
<br />
<input type="radio" name="choice" value="1" />
<br />
<input type="radio" name="choice" value="2" />
<br />
<input type="radio" name="choice" value="3" />
<div>String Output: <span id="outputStr"> </span>
</div>
<div>Array Output: <span id="outputArr"> </span>
</div>

Buttons with values, How to calculate a total price

First I'd like to say that i'm a very new beginner when it comes to java script with no other skills involved. I seem to be a little lost in my coding. I have two sets of options with three choices within each. Each choice has its own price. How do I calculate a total price?
JavaScript (included in HEAD)
var theForm = document.forms["pizzaOrder"];
var pizza_price = new Array();
pizza_price["meatLover"] = 15.50;
pizza_price["veggieLover"] = 12.50;
pizza_price["supreme"] = 20.00;
function getPizzaPrice() {
var pizzaPrice = 0;
var theForm = document.forms["pizzaOrder"]; //You already declared "theForm" at global scope - no need to redeclare it here to hold the same reference -crush
var pizzaType = theForms.elements["pizzaType"]; //Mispelled "theForm" here -crush
for(var i = 0; i < pizzaType.length; i++) {
if(pizzaType[i].checked) {
pizzaPrice = pizza_price[pizzaPrice[i].value];
break;
}
}
return pizzaPrice;
}
var extra_top = new Array()
extraTop["extraChees"] = 1.00;
extraTop["mushrooms"] = 1.10;
extraTop["anchovies"]-1.25; //Obvious syntax error here -crush
function getToppingPrice() {
var toppingPrice=0;
var theForm = document.forms["pizzaOrder"];
var extraTop = theForm.elements["extraTop"] //You forgot the semi-colon here -crush
for(var i = 0; i < extraTop.length; i++) {
if(extraTop[i].checked) {
toppingPrice = extra_top[extraTop.value];
break;
}
}
return toppingPrice;
}
function getTotal() //You're missing an opening bracket here -crush
var pizzaPrice = getPizzaPrice() + getToppingPrice();
document.getElementbyId('totalPrice').innerHTML = "Total Price for Pizza is $" + pizzaPrice;
//You're missing a closing bracket here -crush
HTML
<body onload="hideTotal">
<h1>Pizza To Go</h1>
<h2>Order Online</h2>
<form action="" id="PizzaOrder" onsubmit="return false;">
<p>Select Your Pizza!<br />
<input type="radio" name="pizzaType" value="meatLover" onclick="calculateTotal()"/> Meat Lover $12.50<br />
<input type="radio" name="pizzaType" value="veggieLover" onclick="calculateTotal()"/> Veggie Lover $12.50<br />
<input type="radio" name="pizzaType" value="supreme" onclick="calculateTotal()"/> Supreme $12.50<br />
<p>Add Extra Toppings!<br />
<input type="checkbox" name="extraTop" value="extraCheese" onclick="calculateTotal()"/> Extra Cheese $1<br />
<input type="checkbox" name="extraTop" value="mushrooms" onclick="calculateTotal()"/> Mushrooms $1.10<br />
<input type="checkbox" name="extraTop" value="anchovies" onclick="calculateTotal()"/> Anchovies $1.25<br />
</form>
</body>
I'm currently lost as it just doesnt seem to work. Any help is much appreciated.
Your code could stand to be cleaned up quite a bit in general, but your functional issue is that you should be using an object instead of arrays to hold your item prices. Cleanup notwithstanding, try something like this:
var pizza_price = {
"meatLover": 15.50,
"veggieLover": 12.50,
"supreme": 20.00
};
var extra_top = {
"extraChees": 1.00,
"mushrooms": 1.10,
"anchovies": -1.25
};
function getPizzaPrice() {
var pizzaPrice=0;
var theForm = document.forms["pizzaOrder"];
var pizzaType = theForms.elements["pizzaType"];
for(var i = 0; i < pizzaType.length; i++) {
if(pizzaType[i].checked) {
pizzaPrice += pizza_price[pizzaPrice[i].value];
}
}
return pizzaPrice;
}
function getToppingPrice() {
var toppingPrice=0;
var theForm = document.forms["pizzaOrder"];
var extraTop = theForm.elements["extraTop"];
for(var i = 0; i < extraTop.length; i++) {
if(extraTop[i].checked) {
toppingPrice += extra_top[extraTop[i].value];
}
}
return toppingPrice;
}
function getTotal() { return getPizzaPrice() + getToppingPrice(); }
If you want to create a jsfiddle I'll take a closer look.

Categories

Resources