how to store the checked value from checked box and radio box in local storage - javascript

I am using JQuery Mobile
I want to display the value in another page which i get from local storage
It Should been check which is been checked in page1
In HTML5:-
<div data-role="page" id="page1">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" value="One" name="one" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" value="None" name="one" checked="checked" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="Two" id="radio-choice-h-2a" value="On" checked="checked" class="custom2">
<label for="radio-choice-h-2a">On</label>
<input type="radio" name="Two" id="radio-choice-h-2b" value="Off" class="custom2">
<label for="radio-choice-h-2b">Off</label>
</fieldset>
</form>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" name="checkbox-h-2c" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2a" value="on" class="custom2">
<label for="radio-choice-h-2a">Steward</label>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2b" value="off" class="custom2">
<label for="radio-choice-h-2b">Guest</label>
</fieldset>
</form>
</div>
</div>
</div>
In Jquery:-
function getRadioCheckedValue(radio_name)
{
var oRadio = $("input[type='radio']");
for(var i = 0; i < oRadio.length; i++)
{
if(oRadio[i].checked)
{
//return oRadio[i].value;
localStorage.setItem("mode", oRadio[i].value);
}
}
return '';
}
function showSelectedNames(){
var count = $("#checkid input:checked").length;
var str = '';
for(i=0;i<count;i++){
if(i == count-1){
str += $("#checkid input:checked")[i].value;
localStorage.setItem("level", str);
}
else{
str += $("#checkid input:checked")[i].value+',';
localStorage.setItem("level", str);
}
}
//alert("You selected----"+str);
}
Now Plz help me out how to set the value in Page 2 which is been checked in Page1

The simplest way is to store values of checkboxes and radio buttons into an array and then save it to localStorage. However, note that localStorage doesn't accept arrays, so you need to JSON.stringify() before saving it into localStorage and then JSON.parse() to convert it back into a readable array.
Here is how you can collect values of all checkboxes and radio buttons, store them and then read them on next page.
$(document).on("pagebeforehide", "[data-role=page]", function () {
// variables
var elements = [],
id = '',
value = '';
// push values of checkboxes and radio buttons into an array
$("[type=checkbox], [type=radio]", this).each(function () {
id = $(this)[0].id;
value = $(this).prop("checked");
elements.push({
"id": id,
"value": value
});
});
// convert array into a string
// in order store it into localStorage
localStorage["values"] = JSON.stringify(elements);
});
$(document).on("pagebeforeshow", "[data-role=page]", function () {
// active page
var active = $.mobile.activePage;
// parse array of checkboxes and radio buttons
var read_array = JSON.parse(localStorage["values"]);
// check/uncheck checkboxes and radio buttons
$.each(read_array, function (e, v) {
var check_id = "#" + v.id,
check_value = v.value;
$(check_id, active).prop("checked", check_value).checkboxradio("refresh");
});
});
Note: elements id should be the same on other pages.
Demo

Related

One submit button works on my form the other one refreshes the website while updating the url

Im trying to make a quiz using forms and the top submit button works perfectly while the bottom button does not work it ends up refreshing the page and it says the field selected in the address bar this is for a project for college and im a beginner to JavaScript if someone could help me out and explain how it works that would be great I understand how the script works with one from and one button and what the code does but im confused when it comes to 2 forms
var form = document.querySelector("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
form.addEventListener("submit", function(event) {
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText = output;
event.preventDefault();
pointsAdd();
}, false);
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<header>
<ul class="navbar">
<li>Home</li>
<li>Poland</li>
<li>Russia</li>
<li>Uzbekistan</li>
</ul>
</header>
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log">
</pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>
You have TWO forms. so you need an event handler for each
You have ONE log element so I suggest you might want to append the result
Move the preventDefault to the top of the handler to not have a later error submit the form
NOTE: Header ALSO goes in the body (but is irrelevant to your question).
var forms = document.querySelectorAll("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
forms.forEach(form => form.addEventListener("submit", function(event) {
event.preventDefault();
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText += output;
pointsAdd();
}))
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log"></pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>

How to get the checked radio button in JS?

I have seen that this works for most of users, but for some reason it doesn't for me. I use Google Chrome.
radioBut = document.querySelector(".rad-design")
getColor = function(){
for (i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i)
}
}
Html
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
</div>
</form>
The selector should be document.querySelectorAll to get inputs as array and you should target to .rad-input class which is the input and not .rad-design which is the label. Also you should use checked for the inputs to make the input checked, its not check. Also you cannot set checked to two inputs with same name. If thats done only the last input with that name will be checked.
Working Fiddle
const radioBut = document.querySelectorAll(".rad-input")
getColor = function () {
for (i = 0; i < radioBut.length; i++) {
if (radioBut[i].checked) {
console.log(radioBut[i])
}
}
}
<form id="rad">
<div class="radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" checked name="colList">
<div class="rad-design">One</div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design">Two</div>
</label>
</div>
<button type="button" onclick="getColor()">getColor</button>
</form>
document.querySelector returns just one element not an array/list, so in the for loop at i<radioBut.length radioBut.length is undefined, you need to use document.querySelectorAll() instead.
Also I noticed you have selected the div and not the input and you have a couple of syntax errors.
Maybe this can help you:
const radioBut = document.querySelectorAll(".rad-input")
const getColor = function(){
for (let i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i].value)
}
}
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>
Another options is to use the form element functionality
const form = document.getElementById('rad');
const getColor = function(){
return form.colList.value;
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>

How to get a value and label in a textbox

function radioVal(){
//var radVal = document.mainForm.rads.value;
var radVal = document.getElementsByName("rads").value;
result.innerHTML = 'You selected: '+radVal;
}
<div class="pres">
<input type="radio" id="radio01" name="rads" value="10" checked />
<label for="radio01" class="dis"><span>1 time service</span></label>
</div>
<div class="pres">
<input type="radio" id="radio02" name="rads" value="20" />
<label for="radio02" class="dis"><span>Every week</span></label>
</div>
<div class="pres">
<input type="radio" id="radio03" name="rads" value="15" />
<label for="radio03" class="dis"><span>Every 2 weeks </span></label>
</div>
<div class="pres">
<input type="radio" id="radio04" name="rads" value="10" />
<label for="radio04" class="dis"><span>Every 4 weeks</span></label>
</div>
<input type="text" value="" id="result" name="perce" />
<input type="text" value="" id="txtservV" name="servicename" />
<input type="text" value="" id="final_pay" name="final_pay" />
Hello i am using this function to get the value of a selected radio button in a textfield name perce and its value in a field name servicename any one help me in it to sourt it out. I am using this function in doucument.ready function.
Use Document.getElementsByName function which returns array of elements (or better collection, array-like object), so that you can access value of input by index (0 in your case):
var perceVal = document.getElementsByName("perce")[0].value
In case of radio buttons you have to iterate through elements and find which one is checked:
var rads = document.getElementsByName("rads");
var radsValue;
for (var i = 0; i < rads.length; i++) {
if (rads[i].checked) {
radsValue = rads[i].value // here is checked radio
break;
}
}

Getting all child input elements within a div

I am trying to get all the values of the input fields. The issue is all of the <input type=radio/> are dynamic and can increase or decrease at any time.
So I am starting with the main DI and going from there. The problem I have now is I am not getting the input radio buttons values.
So here are the steps I am intending to accomplish:
If any radio button is selected, pass its value to the checkbox value,
If the radio button is selected and the checkbox is not selected, do not pass to the checkbox value
I am looking for a solution in JavaScript only - do not use jQuery
Here is my jsFiddle code
HTML
<div style="display: block;" id="mymainDiv" class="fullFloat">
<input type="hidden" value="1" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">UPS<a class="fRight" onclick="localG('10',false,0,false,'UPS','1','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_UPS"><div class="loadingcheckout"></div></div>
<div id="Price_UPS">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11098" id="deliveryMethodId_1" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
UPS Ground (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="UPS_11098">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="UPS">
</div>
<input type="hidden" value="2" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">Standard<a class="fRight" onclick="localG('20',false,0,false,'Standard','2','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_Standard"><div class="loadingcheckout"></div></div>
<div id="Price_Standard">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11117" id="deliveryMethodId_2" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
Standard Delivery - 2-3 Day Delivery at Ground Rate (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="Standard_11117">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="Standard">
</div>
<input type="hidden" value="3" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">FedEx<a class="fRight" onclick="localG('190',false,0,false,'FedEx','3','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_FedEx"><div class="loadingcheckout"></div></div>
<div id="Price_FedEx">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11088" id="deliveryMethodId_3" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
FedEx Ground (Order by 8:00 PM EST)
</span>
<div class="wrapRight">
<div id="FedEx_11088">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="FedEx">
</div>
</div>
<input type="checkbox" name="shipmode" id="shipmode" value="" onclick="getpref('mymainDiv');">Get Value
JS Code
This executes when the checkbox is clicked:
function getpref(val) {
var wr = document.getElementById(val);
childElements = wr.childNodes;
//alert(childElements);
for(var i = childElements.length-1; i>=0; i--){
var elem = childElements[i];
console.log(elem.id);
if(elem.id && elem.id.indexOf(val+'_')==0){
elem.style.display = 'block';
}
}
//alert(val);
}
You can directly access input nodes in your DIV with getElementsByTagName
function getpref(val) {
var divNode = document.getElementById(val);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i){
var inputNode = inputNodes[i];
if(inputNode.type == 'radio') {
//Do whatever you want
if(inputNode.checked) {
//Do whatever you want
}
}
}
}
Example: http://jsfiddle.net/88vp0jLw/1/
You can use getElementsByName to get you all of the radio buttons by name='deliveryMethodId' and then go from there:
function getpref(val) {
var radioButtons = document.getElementById(val).getElementsByName("deliveryMethodId");
for(var i = radioButtons.length-1; i>=0; i--)
{
var radioButton = radioButtons[i];
if(radioButton.checked)
console.log(radioButton.id + " is selected ");
}
}

How to serialize checkbox value through searilizedarray()?

My question is how to serialize checkbox value and textbox value together in one array through searilizedarray()...
now i am getting something like this
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"Option one"},
{"name":"wpc_chkbox[]","value":"Option two"},
{"name":"wpc_chkboxasdf[]","value":"Option one"},
{"name":"wpc_chkboxasdf[]","value":"Option two"},
{"name":"wpc_inline_chkbox[]","value":"1"},
{"name":"wpc_inline_chkbox[]","value":"2"},
{"name":"wpc_inline_chkbox[]","value":"3"},
{"name":"wpc_radios","value":"Option one"}]
but it should be like
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
{"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
{"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
{"name":"wpc_radios","value":"Option one"}]
i am using var form = $('.wpc_contact').serializeArray(); to get form data
this is my html sample which I am generating dynamically using drag and drop future..
<form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
<fieldset>
<div id="legend" class="">
<legend class="">Demo</legend>
<div id="alert-message" class="alert hidden" style="color: red;"></div>
</div>
<div class="control-group">
<label class="control-label">Checkboxes</label>
<div class="controls" name="wpc_chkbox" req="yes">
<input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes"> Option one
<input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes"> Option two
</div>
</div>
<div class="control-group">
<div class="controls" name="wpc_inline_chkbox" req="yes">
<input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
<input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
<input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
Thanks in advance
Try this:
var cacheObject = {};//tmp cache for form elements name/values pairs
var serArr = $('.wpc_contact').serializeArray();
//set values of elements to cacheObject
$.each(serArr, function (arrayIndex,obj) {
if (cacheObject[obj.name]) {
cacheObject[obj.name].push(obj.value);
} else {
cacheObject[obj.name] = [obj.value];
}
});
//create new serialized array
var newSerArr = [];
$.each(cacheObject, function (key, value) {
var obj = {};
obj[key] = value;
newSerArr.push(obj);
});
console.log(newSerArr);//looks like serializeArray
This one makes a different array and elements of same name are grouped together.
var form_data = $(".wpc_contact").serializeArray();
var form_array = {}; //final array where all the values will be stored
$.each(form_data, function(i, element) {
if(jQuery('input[name="'+element.name+'"]:checked').length>0)
{
replaced = element.name.replace('[]',''); //removing [] from the input name
form_array[replaced]={};
jQuery('input[name="'+element.name+'"]:checked').each(function(j,ind){
form_array[replaced][j] = jQuery(this).val();
});
}
else
{
form_array[element.name] = element.value;
}
});
console.log(form_array);
You can access as:
alert(form_array['wpc_chkbox'][0]); //no '[]' in the key

Categories