Save and restore settings on Chrome - javascript

I have
options.html
<html>
<head>
<meta charset="utf-8">
<title>Options</title>
<script src="js/options.js"></script>
</head>
<body>
<p>
<input type="checkbox" name="checkbox" id="checkbox">
<label for="checkbox">Test</label></p>
<p>
<label for="textfield">Filter:</label>
<input type="text" name="textfield" id="textfield">
</p>
<p>Select type:</p>
<p>
<label>
<input type="radio" name="RadioGroup1" value="True" id="RadioGroup1_0">
Radio</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="False" id="RadioGroup1_1">
Radio</label>
</p>
<p>
<button id="BtnSave">Save</button>
<button id="BtnRestore">Restore</button>
<br>
</p>
</body>
</html>
options.js
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("BtnSave").addEventListener("click", ButtonSave);
document.getElementById("BtnRestore").addEventListener("click", ButtonsRestore);
});
function ButtonSave() {
var ... = document.getElementById('...').checked;
chrome.storage.sync.set({...: ...}, function() {
});
}
function ButtonsRestore() {
chrome.storage.sync.get(likesColor, function (retVal) {
});
}
How save: CheckBox status, value in Edit and RadioGroup ItemIndex?
How restore: CheckBox (Checked := True), Edit (Text := 'bla-bla') and RadioGroup (ItemIndex := 1)?
Thanks!

The "checked" property of both checkboxes and radio buttons will let you see if they are selected:
console.log(document.getElementById(id).checked)
You can also use this to programmatically set them, e.g.
document.getElementById(id).checked = true
For text boxes, their current value is in the value property:
console.log(document.getElementById(id).value)
and likewise can be set:
document.getElementById(id).value = "whatever"

Solved
function save_options() {
var elements = document.getElementsByName('RadioGroup1');
for (i = 0; i < elements.length; i++) {
if (elements[i].checked) {
localStorage.setItem("RadioGroup1", elements[i].value);
break;
}
}
}
function restore_options() {
var elements = document.getElementsByName('RadioGroup1');
var num = localStorage.getItem("RadioGroup1");
elements[num].checked = true;
}

Related

How to limit the number of checked checkbox in jQuery? [duplicate]

I have the following HTML:
<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>
Live site:
http://www.chineselearnonline.com/amember/signup20.php
How can I do it so that the user can only select 3 of those checkboxes?
Using change event you can do something like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
See this working demo
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
Try this DEMO:
$(document).ready(function () {
$("input[name='vehicle']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='vehicle']:checked").length;
if (cnt > maxAllowed)
{
$(this).prop("checked", "");
alert('Select maximum ' + maxAllowed + ' Levels!');
}
});
});
$('.checkbox').click(function(){
if ($('.checkbox:checked').length >= 3) {
$(".checkbox").not(":checked").attr("disabled",true);
}
else
$(".checkbox").not(":checked").removeAttr('disabled');
});
i used this.
I think we should use click instead change
Working DEMO
$("input:checkbox").click(function(){
if ($("input:checkbox:checked").length > 3){
return false;
}
});
Working DEMO
Try this
var theCheckboxes = $(".pricing-levels-3 input[type='checkbox']");
theCheckboxes.click(function()
{
if (theCheckboxes.filter(":checked").length > 3)
$(this).removeAttr("checked");
});
I'd say like letiagoalves said, but you might have more than one checkbox question in your form, so I'd recommend to do like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($('input.single-checkbox').siblings('input.single-checkbox:checked').length > limit) {
this.checked = false;
}
});
(function ($) {
$(document).ready(function () {
$(document).on("change", ".pricing-levels-3 input", function () {
var numberOfChecked = $(".pricing-levels-3 input:checkbox:checked").length;
if (numberOfChecked >= 2) {
$(".pricing-levels-3 input:not(:checked)").prop("disabled", true);
} else {
$(".pricing-levels-3 input:not(:checked)").removeAttr("disabled", true);
}
});
});
})(jQuery);
This is working for me with checkbox name.
<script>
// limit checkbox select
$('input[name=vehicle]').on('change', function (e) {
if ($('input[name=vehicle]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
</script>
This is how I made it work:
// Function to check and disable checkbox
function limit_checked( element, size ) {
var bol = $( element + ':checked').length >= size;
$(element).not(':checked').attr('disabled',bol);
}
// List of checkbox groups to check
var check_elements = [
{ id: '.group1 input[type=checkbox]', size: 2 },
{ id: '.group2 input[type=checkbox]', size: 3 },
];
// Run function for each group in list
$(check_elements).each( function(index, element) {
// Limit checked on window load
$(window).load( function() {
limit_checked( element.id, element.size );
})
// Limit checked on click
$(element.id).click(function() {
limit_checked( element.id, element.size );
});
});
I have Alter this function to auto uncheck previous
var limit = 3;
$('.compare_items').on('click', function(evt) {
index = $(this).parent('td').parent('tr').index();
if ($('.compare_items:checked').length >= limit) {
$('.compare_items').eq(localStorage.getItem('last-checked-item')).removeAttr('checked');
//this.checked = false;
}
localStorage.setItem('last-checked-item', index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="compare_items">1
<input type="checkbox" class="compare_items">2
<input type="checkbox" class="compare_items">3
<input type="checkbox" class="compare_items">4
<input type="checkbox" class="compare_items">5
<input type="checkbox" class="compare_items">6
<input type="checkbox" class="compare_items">7
<input type="checkbox" class="compare_items">8
<input type="checkbox" class="compare_items">9
<input type="checkbox" class="compare_items">10
I did this today, the difference being I wanted to uncheck the oldest checkbox instead of stopping the user from checking a new one:
let maxCheckedArray = [];
let assessmentOptions = jQuery('.checkbox-fields').find('input[type="checkbox"]');
assessmentOptions.on('change', function() {
let checked = jQuery(this).prop('checked');
if(checked) {
maxCheckedArray.push(jQuery(this));
}
if(maxCheckedArray.length >= 3) {
let old_item = maxCheckedArray.shift();
old_item.prop('checked', false);
}
});
This method works well with checkboxes in a container, such as bootstrap checkbox
const checkedLimmit = 2;
function ValidateCheckBoxGroup(container) {
if (container.find('input[type="checkbox"]:checked').length >= checkedLimmit) {
container.find('input[type="checkbox"]:not(:checked)').prop('disabled', true);
container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').addClass('disabled');
} else {
container.find('input[type="checkbox"]:not(:checked)').prop('disabled', false);
container.find('input[type="checkbox"]:not(:checked)').closest('div.checkbox').removeClass('disabled');
}
}
$(function () {
// validate containers on page load
$('div.checkbox-group').each(function () {
ValidateCheckBoxGroup($(this));
});
// set checkbox events
$('div.checkbox-group input[type="checkbox"]').change(function () {
ValidateCheckBoxGroup($(this).closest("div.checkbox-group"));
});
});
JS and HTML
This worked for me what it does is that, the onclick function checkControl() will count the number of times the checkbox has been clicked then if it's greater than 3 display error message.
function checkboxControl(j) {
var total = 0;
var elem = document.getElementsByClassName("checkbox");
var error = document.getElementById("error");
for (var i = 0; i < elem.length; i++) {
if (elem[i].checked == true) {
total = total + 1;
}
if (total > 3) {
error.textContent = "You Must Select at Least 3";
elem[j].checked = false;
return false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="">
<span id="error" style="color: red"></span>
<br>
<span>Python</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(0)"
id="1"
/>
<br>
<span>Javascript</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(1)"
id="1"
/><br>
<span>Go</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(2)"
id="1"
/><br>
<span>Laravel</span>
<input
type="checkbox"
class="checkbox"
name="interest[]"
onclick="checkboxControl(3)"
id="1"
/>
</form>
</body>
</html>
This resources helped me understand
https://www.plus2net.com/javascript_tutorial/checkbox-limit-demo2.php
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
This function simply checks if you have just checked a checkbox. If yes, it increments the checked value by one. If it reaches the limit then the next checkbox is rejected.
var limit = 3;
var checked = 0;
$('.single-checkbox').on('change', function() {
if($(this).is(':checked'))
checked = checked+1;
if($(this).is(':checked') == false)
checked = checked-1;
if(checked > limit) {
this.checked = false;
checked = limit;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pricing-levels-3">
<p><strong>Which level would you like? (Select 3 Levels)</strong></p>
<input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
<input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
</div>

Output a radio button in a webpage

I'm trying to input the value of the checked radio button as one of a functions parameres (here sign). This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="proj4js/lib/proj4js/lib/proj4js-compressed.js"></script>
</head>
<body>
<script>
function func1 (x,y, sign){
var z=(x+y)*sign
document.getElementById("Z").innerHTML = z;
}
</script>
<form >
first input:<br>
<input id="Y" type="text" y="Y" value=85>
<br>
second input:<br>
<input id="X" type="text" x="X" value=15>
<br>
<input type="radio" name="hem" value=1 id = "N" >north
<input type="radio" name="hem" value=-1 id = "S" >south
The Answer:<br>
<input id="Z" type="text" z="Z" >
<br><br>
</form>
<button type="button" onclick="func1(Number(document.getElementById('X').value),Number(document.getElementById('Y').value), ?? )"> try it </button>
I don't know what to put instead of ?? ? The sign determines if sign is positive or negative.
make input elements as
<form id="demoForm">
first input:<br>
<input id="Y" type="text" value=85>
<br>
second input:<br>
<input id="X" type="text" value=15>
<input type="radio" name="hem" value="1" id="N" >north
<input type="radio" name="hem" value="-1" id ="S" >south
The Answer:<br>
<input id="Z" type="text" z="Z" >
</form>
<script>
function getRadioVal(form, name) {
var val;
// get list of radio buttons with specified name
var radios = form.elements[name];
// loop through list of radio buttons
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked ) { // radio checked?
val = radios[i].value; // if so, hold its value in val
break; // and break out of for loop
}
}
return val; // return value of checked radio or undefined if none checked
}
var val = getRadioVal( document.getElementById('demoForm'), 'hem' );
alert(val); //you can pass this value as parameter
</script>
The simple way would be to write a helper function to collect your paramters and then call your function from this function.
You could use jQuery to get the value of the checked
$('input[name=hem]:checked').val()
Just need to make sure that the form you're using has an id. Then you wouldn't have to pass to the function just get the value directly from the form in your function.
<script>
function func1 (x,y){
var sign = $('input[name=hem]:checked').val();
var z=(x+y)*sign;
document.getElementById("Z").innerHTML = z;
}
</script>
<!DOCTYPE html>
<html>
<head>
<!--
<script src="proj4js/lib/proj4js/lib/proj4js-compressed.js"></script>
-->
</head>
<body>
<form >
first input:<br>
<input id="Y" type="text" y="Y" value=85>
<br>
second input:<br>
<input id="X" type="text" x="X" value=15>
<br>
<input type="radio" name="hem" value="1" id="N" >north</input>
<input type="radio" name="hem" value="-1" id="S" >south </input>
The Answer:<br>
<input id="Z" type="text" z="Z" >
<br><br>
</form>
<button type="button" onclick="func1(Number(document.getElementById('X').value),Number(document.getElementById('Y').value), getAppropriateValue() )"> try it </button>
<script>
function func1 (x,y, sign){
var z=(x+y)*sign
document.getElementById("Z").value = z;
}
function getAppropriateValue(){
var result = 0;
var checkboxN = document.getElementById('N');
var checkboxS = document.getElementById('S');
if(checkboxN && checkboxN.checked) result = 1;
if(checkboxS && checkboxS.checked) result = -1;
return result;
}
</script>
You can entirely take off third param and can output sign based on radio checked property.
<script>
function func1 (x,y) {
var z=(x+y);
if(document.getElementById("N").checked) {
z= z*1;
}elseif(document.getElementById("N").checked) {
z=z*-1;
}
document.getElementById("Z").value = z;
}
</script>

Undefined error in Mozilla Firefox

Why I'm getting undefined error in Firefox and IE. This code works well in Google Chrome. Here is the full code http://liveweave.com/fUhpiI
this is my html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/hpstyles.css" rel="stylesheet">
<script src="js/hpjs.js"></script>
</head>
<body>
<form id="hp">
<div>
<h2>1. Which one do you prefer?</h2>
<div>
<input type="radio" name="q1" id="radio1" class="radio" value="9"/>
<label for="radio1">Tea</label>
</div>
<div>
<input type="radio" name="q1" id="radio2" class="radio" value="4"/>
<label for="radio2">Coffee</label>
</div>
<div>
<input type="radio" name="q1" id="radio3" class="radio" value="1"/>
<label for="radio3">Milk</label>
</div>
</div>
<div>
</br>
<div><div>
<button type="button" onclick="hp(this.form)">Check</button>
<input class="reset" type="reset" value="Reset">
</div></div></div>
</form>
<div id="result"></div>
<div id="total"></div>
</body>
</html>
this is javascript
function hp(form)
{
var count1=0, count2=0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0,a ;
for(var i=0;i<3;i++){
if (form.q1[i].checked === true)
{
count1++;
}
}
if(count1!==1){
alert("Please Answer 1st Question");
return false;
}
answer1 = (form.q1.value);
a=Math.floor(answer1);
document.getElementById("result").innerHTML= "The selected values are "+"</br>"+answer1;
}
you should declare a answer variable .and you should access "q1" elements by giving index since you have 3 "q1" elements .basically form.q1 is a object NodeList .you can't get value from object NodeList.so actually in your case you should add brake to for loop and find the clicked radio button index .
you should use
answer1 = form.q1[i].value;
instead of
answer1 = form.q1.value;
explain
form.q1 is a object NodeList so
form.q1.value --> undefined since object NodeList/collection has no property "value"
and
form.q1[0] --> HTMLInputElement so
form.q1[0].value --> is not undefined
fixed code .WORKING DEMO http://jsfiddle.net/madhawa11111/3rywkdvf/
function hp(form) {
var i;
var answer;
var count1 = 0,count2 = 0,count3 = 0,count4 = 0,count5 = 0,count6 = 0,count7 = 0,count8 = 0,count9 = 0,count10 = 0, a;
for (i = 0; i < 3; i++) {
if (form.q1[i].checked === true) {
count1++;
break;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
answer1 = form.q1[i].value; //error was here .
a = Math.floor(answer1);
document.getElementById("result").innerHTML = "The selected values are " + "</br>" + answer1;
}
if it worked in google chorm that's because browsers ignore some errors.

Passing a form value to a JavaScript Function

I have read through lots of postings here and around the net, and I even have books covering this subjective, but I just can't get it to work. I just can't get the Function to pick up the value of the "RadioDrink" variable. I have tried all sorts of combinations Using DOM methods like below and here using a collection (this) and (form) with no luck.
Any help would be appreciated.
function ValDrink(form){
if (form.RadioDrink.value == "soup")
{
alert("Its soup OK!");
return true; // OK
}
======================here is my code.======================
<html>
<head>
<title>Test</title>
<script type="text/JavaScript">
<!--
function ValDrink()
{
if (document.forms.Drinks.RadioDrink.value == "soup")
{
alert("Its soup OK!");
return true; // soup
}
else
{
alert("OK");
return false; // not soup
}
}
//-->
</script>
</head>
<body>
<form method="post" id="Drinks" name="Drinks" onsubmit="return ValDrink()">
<input type="radio" checked name="RadioDrink" value="Tea">Tea<br>
<input type="radio" name="RadioDrink" value="Coffee">Coffee<br>
<input type="radio" name="RadioDrink" value="Soup">Soup<br>
<input type="checkbox" name="CheckMilk" value="Yes">Milk
<input type="checkbox" name="CheckSugar" value="Yes">Sugar
<br>
<input type="submit" name="OKButton" value="Vend">
</form>
</body>
</html>
This will give the value of "Soup" checkbox:
document.forms["Drinks"]["RadioDrink"][0].checked
you need to do this in a different way. first of all your DOM is showing undefined value. you can add different ids to the radio buttons. you can do it like below
<html>
<head>
<title>Test</title>
<script type="text/JavaScript">
<!--
function ValDrink()
{
if (document.getElementById("Rsoup").checked == true)
{
alert("its soup");
return true; // soup
}
else
{
alert("its not soup");
return false; // not soup
}
}
//-->
</script>
</head>
<body>
<form method="post" id="Drinks" name="Drinks" onsubmit="return ValDrink()">
<input type="radio" checked name="RadioDrink" value="Tea">Tea<br>
<input type="radio" name="RadioDrink" value="Coffee">Coffee<br>
<input type="radio" name="RadioDrink" id="Rsoup" value="Soup">Soup<br>
<input type="checkbox" name="CheckMilk" value="Yes">Milk
<input type="checkbox" name="CheckSugar" value="Yes">Sugar
<br>
<input type="submit" name="OKButton" value="Vend">
</form>
</body>
</html>
The problem is that this:
document.forms.Drinks.RadioDrink
returns an array-like reference to all three inputs with that name, it doesn't return a reference to the currently selected one. So you can't just test the value property.
The easiest to explain way to achieve what you want to do is to give the radio buttons unique ids:
<input type="radio" checked name="RadioDrink" id="RadioDrinkTea" value="Tea">Tea<br>
<input type="radio" name="RadioDrink" id="RadioDrinkCoffee" value="Coffee">Coffee<br>
<input type="radio" name="RadioDrink" id="RadioDrinkSoup" value="Soup">Soup<br>
And then directly select the one you want to test:
if (document.getElementById("RadioDrinkSoup").checked) {
alert("It's soup OK!");
return true; // soup
} else {
alert("OK");
return false; // not soup
}
Try your coding like below... it will help you.....
<html>
<head>
<title>Test</title>
<script type="text/JavaScript">
<!--
function ValDrink() {
var radios = document.getElementsByName('RadioDrink');
var radioName;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
radioName = radios[i].value;
}
}
if (radioName.toUpperCase() == "soup".toUpperCase())
{
alert("Its soup OK!");
return true; // soup
}
else
{
alert("OK");
return false; // not soup
}
}
//-->
</script>
</head>
<body>
<form method="post" id="Drinks" name="Drinks" onsubmit="return ValDrink()">
<input type="radio" checked name="RadioDrink" value="Tea">Tea<br>
<input type="radio" name="RadioDrink" value="Coffee">Coffee<br>
<input type="radio" name="RadioDrink" value="Soup">Soup<br>
<input type="checkbox" name="CheckMilk" value="Yes">Milk
<input type="checkbox" name="CheckSugar" value="Yes">Sugar
<br>
<input type="submit" name="OKButton" value="Vend">
</form>
You should check for each value in the radio group & use it instead. Something like :
function getCheckedRadio(radio_group) {
for (var i = 0; i < radio_group.length; i++) {
var button = radio_group[i];
if (button.checked) {
return button;
}
}
return undefined;
}
Call it to get selected value. So In your case :
getCheckedRadio(document.forms.Drinks.RadioDrink);
Not a right way to get radios value. Use the following function, also can check this question
function ValDrink()
{
var radios =document.forms.Drinks.RadioDrink;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked && radios[i].value==="Soup") {
alert("Its soup OK!"); // soup
return true;
}
}
alert("OK");
return false; // not soup
}

How to get the checked option in a group of radio inputs with JavaScript?

How to get the checked option in a group of radio inputs with JavaScript?
<html>
<head>
<script type="text/javascript">
function testR(){
var x = document.getElementsByName('r')
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert('Option selected: ' + x[k].value)
}
}
</script>
</head>
<body>
<form>
<input type="radio" id="r1" name="r" value="1">Yes</input>
<input type="radio" id="r2" name="r" value="2">No</input>
<input type="radio" id="r3" name="r" value="3">Don't Know</input>
<br/>
<input type="button" name="check" value="Test" onclick="testR()"/>
</form>
</body>
</html>
http://www.somacon.com/p143.php
If you need the actual element and not just the selected value, try this:
function findSelected(){
for (i=0;i<document.formname.radioname.length;i++){
if (document.formname.radioname[i].checked){
return document.formname.radioname[i];
}
}
}
generic functions (loosely based on yours )
function getRadioGroupSelectedElement(radioGroupName) {
var radioGroup = document.getElementsByName(radioGroupName);
var radioElement = radioGroup.length - 1;
for(radioElement; radioElement >= 0; radioElement--) {
if(radioGroup[radioElement].checked){
return radioGroup[radioElement];
}
}
return false;
}
function getRadioGroupSelectedValue(radioGroupName) {
var selectedRadio = getRadioGroupSelectedElement(radioGroupName);
if (selectedRadio !== false) {
return selectedRadio.value;
}
return false;
}

Categories

Resources