localStorage - Retrieve Checkbox Values - javascript

I'm working with a form (made with Bootstrap 4) and localStorage. I'm using it so i can use the form input values on another page. It works fine with the inputs, but in this form i also have checkboxes and i can't find how to do the following : i'd like to check which checkboxes are checked. For those that are checked, i'd like to add the checkbox label text in the localStorage to use it on my other page. How can i achieve this?
My html looks like this :
<form role="form" id="form" data-toggle="validator">
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputAdresse">Adresse *</label>
<input type="text" class="form-control places-autocomplete" name="inputAdresse" id="inputAdresse"
required="required" placeholder="" value="" autocomplete=" address-line1" />
</div>
</div>
<div class="form-row form-checks">
<div class="form-group col-md-12 col-sm-6">
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input" id="checkAscenseur" name="check" value="Ascenseur">
<label class="custom-control-label" for="checkAscenseur">Ascenseur</label>
</div>
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input" id="checkCave" name="check" value="Cave">
<label class="custom-control-label" for="checkCave">Cave</label>
</div>
<div class="custom-control custom-checkbox mb-2">
<input type="checkbox" class="custom-control-input" id="checkParking" name="check" value="Parking">
<label class="custom-control-label" for="checkParking">Parking</label>
</div>
</div>
</div>
<button class="nextBtn pull-right" type="submit" id="btn-submit">Submit</button>
</form>
For the input, i use the following javascript :
document.getElementById("form").addEventListener("submit", callme);
function callme(event) {
event.preventDefault();
let inputAdresse = document.getElementById('inputAdresse');
localStorage.setItem('inputAdresse', inputAdresse.value);
window.location.href = "thank-you.html";
};

Here is the working DEMO of how to do what you need.
You need to use the checked property for checkboxes:
document.getElementById("form").addEventListener("submit", callme);
function callme(event) {
event.preventDefault();
let inputAdresse = document.getElementById('inputAdresse');
localStorage.setItem('inputAdresse', inputAdresse.value);
let checkAscenseur = document.getElementById('checkAscenseur');
localStorage.setItem('checkAscenseur', checkAscenseur.checked);
let checkCave = document.getElementById('checkCave');
localStorage.setItem('checkCave', checkCave.checked);
let checkParking = document.getElementById('checkParking');
localStorage.setItem('checkParking', checkParking.checked);
window.location.href = "thank-you.html";
};
UPD new code that saves data values instead of true/false: DEMO.

You could also do it the following way (pretty much the same, but a bit more compact):
document.getElementById("form").addEventListener("submit", callme);
function callme(event) {
event.preventDefault();
let inputAdresse = document.getElementById('inputAdresse');
localStorage.setItem('inputAdresse', inputAdresse.value);
new Array(...document.getElementById('form').getElementsByClassName('custom-control-input')).forEach(cb => {
localStorage.setItem(cb.id, cb.checked);
}
window.location.href = "thank-you.html";
}
I convert the HTMLCollection I get from the .getElementsByClassName(...) function to an array, which I can iterate over using .forEach(). If you want to store the values by their ids, this works fine :P

Related

i receive the output value of radio buttons as both on even though one is checked

I only did this code of java script
so maybe I need to do an add event listener but i don't know what I need to do
pick_up:document.getElementById("shippingOption1").value,
delivery:document.getElementById("shippingOption2").value
the output is
pick up:onor
delivery:on
i want so that one of them be on if checked and off if its not checked how can i do that?
html
<div class="custom-control custom-radio">
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio">
<div class="custom-control custom-radio"><input id="shippingOption1" name="shipping-option" class="custom-control-input" checked="checked" type="radio" ">
<label class="custom-control-label" for="shippingOption1">
ps I already tried adding value of 1 and 2 to html code but it only gives 1 and 2 regardless that its not checked
In order to see if a radio button is selected or not, you should use the .checked attribute.
pick_up: document.getElementById("shippingOption1").checked,
delivery: document.getElementById("shippingOption2").checked
For value, you could add the attribute value="delivery" in order to know what is checked without knowing it's id.
Here's a piece of code how it works:
function handleChange() {
const options = {
pick_up: document.getElementById("shippingOption1").checked,
delivery: document.getElementById("shippingOption2").checked
}
const result = document.querySelector('.result');
if (options.pick_up) {
result.textContent = 'You chose pickup';
} else if(options.delivery) {
result.textContent = 'You chose delivery';
}
console.log(options);
};
<div class="custom-control custom-radio">
<input id="shippingOption2" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="delivery">
<label class="custom-control-label" for="shippingOption2">delivery</label>
</div>
<div class="custom-control custom-radio">
<input id="shippingOption1" name="shipping-option" class="custom-control-input" type="radio" onchange="handleChange()" value="pick_up">
<label class="custom-control-label" for="shippingOption1">pick_up</label>
</div>
<div class="result">Select an option</div>
<div class="result2">The value of the selected option is: </div>

foreach loop, make the next input field required

I made a function, which should check whether my input field, with type checkbox has been checked or not... but whenever I check my input field the input fields I wish to make required do not get the required attributes.
I basically tried everything from this topic: jQuery add required to input fields
and read this topic in hopes of finding something: .prop() vs .attr()
but unfortunately none of the topics has helped me much further. So either I made a mistake somewhere in my code, or the required attribute is a bit buggy.
I call the function via my input field (onclick event).
I have already checked whether selectors were correct, and they are.
this is how my HTML looks like:
<div class="row" style="margin: auto;">
<div class="custom-control custom-checkbox col-md-4">
<input class="custom-control-input" onclick="is_required()" type="checkbox" id="fruittariër" value="fruittariër" name="vegetarisch[]">
<label class="custom-control-label" for="fruittariër"> fruittariër</label>
</div>
<div class="col-md-4 input-group leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">€</span>
</div>
<input type="number" step="0.01" class="form-control" placeholder="Kosten" name="vegCosts[]">
</div>
<div class="input-group col-md-4 leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="veganDatePicker"><i class="fas fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="veganEindDatum[]" id="shutDateFruittariër" placeholder="Sluit Datum" aria-label="veganDatePicker" aria-describedby="veganDatePicker">
</div>
</div>
this is how I call my function:
<input class="custom-control-input" onclick="is_required()" type="checkbox" value="vegan" name="vegetarisch[]">
function is_required() {
//check whether the checkbox has been checked or not
//if yes, make the other input fields inside the row required
// variable odin = the row wrapped around the cols
$('input[name="vegetarisch[]"]').each(function(index, thisElement) {
if($(thisElement).is(':checked')) {
let odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', true);
odin.find('input[name="veganEindDatum[]"]').attr('required', true);
} else {
odin = $(thisElement).closest('.row');
odin.find('input[name="vegCosts[]"]').attr('required', false);
odin.find('input[name="veganEindDatum[]"]').attr('required', false);
}
});
}
So what I wish to achieve: When the checkbox is checked I want to have the 2 other input fields inside the row to gain the attribute 'required'.
No need for an each you can pretty much do this in one line with an event handler.
Below, the closest .row is found for the button that was clicked. Then one selector is used to find both inputs that will be required. Then the required prop is set based on the status of the check button.
$(document).ready(function() {
//Handle events on the checkbox
$('input[name="vegetarisch[]"]').on('click', function() {
//get the nearst row
$(this).closest('.row')
//Find the check boxes
.find('input[name="vegCosts[]"],input[name="veganEindDatum[]"]')
//set the required propery if the checkbox is checked
.prop('required', $(this).is(":checked"));
});
});
:required {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="row" style="margin: auto;">
<div class="custom-control custom-checkbox col-md-4">
<input class="custom-control-input" type="checkbox" id="fruittariër" value="fruittariër" name="vegetarisch[]">
<label class="custom-control-label" for="fruittariër"> fruittariër</label>
</div>
<div class="col-md-4 input-group leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">€</span>
</div>
<input type="number" step="0.01" class="form-control" placeholder="Kosten" name="vegCosts[]">
</div>
<div class="input-group col-md-4 leftVeganPadding">
<div class="input-group-prepend">
<span class="input-group-text" id="veganDatePicker"><i class="fas fa-calendar-alt"></i></span>
</div>
<input type="text" class="form-control" name="veganEindDatum[]" id="shutDateFruittariër" placeholder="Sluit Datum" aria-label="veganDatePicker" aria-describedby="veganDatePicker">
</div>
</div>
You may want to try using the onchange event:
<input class="custom-control-input" id="myCheckbox" type="checkbox" value="vegan" name="vegetarisch[]">
$('#myCheckbox').change(function () {
is_required();
});
function is_required() {
let odin = $(thisElement).closest('.row');
$('input[name="vegetarisch[]"]').each(function (index, thisElement) {
if ($(thisElement).is(':checked')) {
odin.find('input[name="vegCosts[]"]').attr('required', true);
odin.find('input[name="veganEindDatum[]"]').attr('required', true);
} else {
odin.find('input[name="vegCosts[]"]').attr('required', false);
odin.find('input[name="veganEindDatum[]"]').attr('required', false);
}
});
}

control input field active status of form using toggle switch

Want the toggle switch to control the form fields when check, below is the sample code please suggest
<div class="form-group row">
<label for="lot-1" class="col-sm-2 col-form-label">x</label>
<div class="col-md-4">
<input type="text" class="form-control numbersOnly" name="lot-1" id="lot-1" placeholder="Result" min="4"
max="4">
<div class="toggleWrapper">
<input type="checkbox" name="toggle1" class="mobileToggle" id="toggleField" checked value="true"
data-id="lot-1">
<label for="toggle1"></label>
</div>
</div>
<div class="col-md-4">
<input type="text" class="form-control numbersOnly" name="lot-2" id="lot-2" placeholder="Result" min="4"
max="4">
<div class="toggleWrapper">
<input type="checkbox" name="toggle1" class="mobileToggle" id="toggleField" checked value="true"
data-id="lot-2">
<label for="toggle1"></label>
</div>
</div>
<div class="col-md-4">
<input type="text" class="form-control numbersOnly" name="lot-3" id="lot-3" placeholder="Result" min="4"
max="4">
</div>
<div class="toggleWrapper">
<input type="checkbox" name="toggle1" class="mobileToggle" id="toggleField" checked value="true" data-id="lot-3">
<label for="toggle1"></label>
</div>
</div>
And below is my jquery handler to make it functional
var fieldValue = false;
$('#toggleField').on('change', function(e) {
var fieldId = $("#toggleField").attr('data-id');
// console.log(fieldValue+fieldId);
if (fieldValue === true) {
// $("input[id=name]").attr('readonly',true);
$('#lot-'+fieldId).attr('readonly',true);
} else {
$('#lot-'+fieldId).attr('readonly',false);
}
});
I was testing to read the attribute data-id for each selected it will make the field disabled / read-only when unchecked by comparing the id with the data-id of respective input.
you can use the following code I changed the selector of change event $('#toggleField') to class name $('.mobileToggle') you have to remove Id attributes from checkboxes because it has the same id which is wrong
and get checked value dynamically to add and remove readonly attribute according to its value selector for inputs was wrong also $('#lot-'+fieldId) it has to be $('#'+fieldId) finally I fired change event manually to run it on first time page load you can add all this code inside document ready
$('.mobileToggle').on('change',function(e){
var fieldId = $(this).attr('data-id');
var fieldValue = $(this).is(':checked');
if(fieldValue == true){
$('#'+fieldId).attr('readonly', 'readonly');
}else{
$('#'+fieldId).removeAttr('readonly');
}
});
$('.mobileToggle').change();

cloning elements with eventlistener

im trying to clone elements when I click the button. So far, I don't know, what the problem is about my code. I think it looks kinda right, could you please look over, and tell/describe me the problem? I mean, I read a lot of documentation about clonenode, and I just do the same. And when I look over my code, it does make sense to me, but it doest want to work... D:
The button should clone the whole field(inputCar)
Here is my fiddle https://jsfiddle.net/7k1sb7w0/
This is the html code:
<button id="buttonBtn">Clone Field</button>
<div id="inputCar">
<div class="column">
<label class="heading">Invite Persons</label>
</div>
<div class="medium-6 column">
<label for="ext-name">Name</label>
<input id="ext-name" type="text">
<input type="checkbox">
<label for="check7"></label>
<label>BMW</label>
<input type="checkbox" checked="true">
<label for="check8"></label>
<label>Ford</label>
</div>
<div class="medium-6 column">
<label for="ext-mail">E-Mail</label>
<input id="e-mail" type="email">
<datalist id="members"></datalist>
<button class="deletePerson">delete</button>
<label class="delete_btn">delete Field</label>
</div>
<br>
</div>
and this is my jsfile:
var clickBtn = document.querySelector('#buttonBtn');
var field = document.querySelector('#inputCar');
var i = 0;
clickBtn.addEventlistener('click', function(e) {
var cloneField = field.cloneNode(true);
cloneField.id = "inputCar" + i++;
field.parentNode.appentChild(cloneField);
}
Thank you in advance,
mark

Javascript radio button not copying fields when clicked

I have a script that is supposed to copy once set of form fields to another when a radio button is checked. It works on Safari, firefox (mac) but not on FF (PC) or IE.
function checkFirstDirAddrs() {
var i;
//checking which radio button selected
for ( i = 0; i < FirstCorpDirAddOption.length; i++) {
if (FirstCorpDirAddOption[i].checked == true) {
switch(i)
{
case 0:
document.getElementById("First_Corp_Director_Address1").value = document.getElementById("Corp_Address1").value;
document.getElementById("First_Corp_Director_Address2").value = document.getElementById("Corp_Address2").value;
document.getElementById("First_Corp_Director_City").value = document.getElementById("Corp_City").value;
document.getElementById("First_Corp_Director_Postal").value = document.getElementById("Corp_Postal").value;
break
case 1:
document.getElementById("First_Corp_Director_Address1").value = '';
document.getElementById("First_Corp_Director_Address2").value = '';
document.getElementById("First_Corp_Director_City").value = '';
document.getElementById("First_Corp_Director_Postal").value = '';
break
}
}
}
}
The html....
<div class="form-group">
<div class="col-sm-10"><strong>*Director Address</strong></div>
<div class="col-sm-6">
<div class="radio">
<label>
<input name="FirstCorpDirAddOption" id="FirstCorpDirAddOption" type="radio" value="Same as Corporate Address" onClick="checkFirstDirAddrs();">
Same as Corporate Address<br>
</label>
<label>
<input name="FirstCorpDirAddOption" id="FirstCorpDirAddOption" type="radio" value="Other" onClick="checkFirstDirAddrs();">
Other <em>(provided below)</em>
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_Address1" class="col-sm-2 control-label">*Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="First_Corp_Director_Address1" name="First_Corp_Director_Address1" maxlength="80">
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_Address2" class="col-sm-2 control-label">Address 2:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="First_Corp_Director_Address2" name="First_Corp_Director_Address2" maxlength="80">
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_City" class="col-sm-2 control-label">*City:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="First_Corp_Director_City" name="First_Corp_Director_City" maxlength="50">
</div>
</div>
<div class="form-group">
<label for="First_Corp_Director_Postal" class="col-sm-2 control-label">*Postal/Zip:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="First_Corp_Director_Postal" id="First_Corp_Director_Postal" maxlength="7">
<span class="help-block">(enter NA if not from Canada/USA)</span>
</div>
</div>
If anyone can shed some more light on the issue that would be great. It works fine on most Mac based browsers I tested on and throws no errors in the Console of dev tools.
As I know there is no standard for treating same ids in one document via global variable.
It's good to know about reference between ids and global variable they initialize. But God please, do not use it. You can use any selector or create different ids instead of trying to get ids with 'FirstCorpDirAddOption'. Just like this, for example:
document.querySelectorAll('.radio input')
Just check what you get via global variable:
Here is Chrome
Here is FF
They are different. Thus you can't use same code for them.
You need to get rid of the duplicate IDs as they are causing you trouble.
You have 3 options if you get rid of the duplicate IDs to still have a 'hook' that JavaScript can use to access the elements.
Option 1: access the elements by name
Option 2: access the elements by a new CSS class name
Option 3: access the elements by some other "loosely defined" method
For simplicity I'm going to recommend #1, but #2 is just as good.
<div class="radio">
<label>
<input type="radio" name="FirstCorpDirAddOption" value="Same as Corporate Address" onclick="checkFirstDirAddrs();"/>
Same as Corporate Address
</label>
<br/>
<label>
<input type="radio" name="FirstCorpDirAddOption" value="Other" onclick="checkFirstDirAddrs();"/>
Other <em>(provided below)</em>
</label>
</div>
Now the JavaScript to access the input(s):
function checkFirstDirAddrs(){
var i;
//checking which radio button selected
var firstCorpDirOptions = document.querySelectorAll('input[name="FirstCorpDirAddOption"]');
for(i=0;i<firstCorpDirOptions.length;i++){
if(firstCorpDirOptions[i].checked == true){
//...

Categories

Resources