Save state radio button javascript-html - javascript

I´m trying to do a program that save the state of the radio button and check it. This is my code but I don´t know what it`s wrong. Help me please
<script>
function saveState(){
var ans1 = document.getElementById('grupo1');
if (ans1.value == 1)
{
ans1.setAttribute("checked","checked");
ans1.checked = true;
}
</script>
<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" onclick="saveState()" value="update">

Try this:
<script>
function saveState(){
var ans1 = document.querySelector('input[name="group"]:checked').value;
if (ans1.value == 1){
ans1.setAttribute("checked","checked");
ans1.checked = true;
}
}
</script>

Being consequent in your approach towards placing brackets helps preventing situations like thisone.
For example, if you place the opening bracket to functions, loops, conditional (if) statements etc on the same line as the condition itself (like you do above at the declaration of the function), you'll only have to look for the closing ones.
On the other hand, if you place both opening and closing brackets on their own line your code will be much more vertically symmetrical, which makes it easier to spot missing brackets if you're dealing with larger chunks of code.
You should check out this article that deals with this particular issue: http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/

You perhaps mean this?
You code does not make much sense unless the grupo1 button can change value
The following script assumes you have a standard cookie script somewhere
<script>
window.onload=function() {
if (getCookie("grupo1")=="true") {
document.getElementById('grupo1').click();
}
// either this
document.getElementById('grupo1').onclick=function() {
setCookie("grupo1","true")
}
// or this - depending on when you want to save the state
document.getElementById("form1").onsubmit=function() {
setCookie("grupo1",document.getElementById('grupo1').checked?"true":"false");
}
}
</script>
<form id="form1">
<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" value="update">
</form>

Related

Input radio elements result always checked

I've searched all the web about it but i couldn't find a solution in javascript without jquery. The problem is the following: I have an entire array of radio elements, which should be checked or unchecked depending on database data. And this is accomplished. Now i have to make the radio button "uncheckable" to change the database data through the form.
I tried to make it in plain javascript as i don't want to think about frontend libraries for the moment.
The html is the following:
<td>
<input class="graphs" name="g4" value="S" defaultvalue="N" checked="true" type="radio">
</td>
<td>
<input class="graphs" name="g5" value="S" defaultvalue="N" type="radio">
The Javascript is the following:
<script type="text/javascript">
window.onload = (function(){
return function(){
var allRadios = document.getElementsByClassName('graphs');
var x = 0;
for(x = 0; x < allRadios.length; x++){
allRadios[x].onclick = function() {
if(this.checked == true){
this.checked = false;
}else{
this.checked = true
}
};
}
}})();
</script>
I've tried to debug and the result is always the same: the first if is executed and always true, even when the element is not checked.
I've tried the same script in jsfiddle and it works right. Is it a problem of my browser?
Thanks in advance.
this.checked == true in else block is not an assignment
If you want a radio to be uncheckable the you can disable it statically, you don't need to use any javascript.
For Unckecked disabled
<input type="radio" name="foo" value="N" disabled>
Four Checked disabled
<input type="radio" name="foo" value="N" checked disabled>

Condtionally disable button by Radio and Checkbox

I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.

Radio button with jQuery and AJAX

I've got the following error when i'm sending the form, to be exact with radio button input.
Here is the HTML Code:
<input name="radio" type="radio" class="raido-btn" id="coral1" value="coral1" />
<label for="coral1">CORAL I</label>
<input name="radio" type="radio" class="raido-btn" id="coral2" value="coral2" />
<label for="coral2">CORAL II</label>
<input name="radio" type="radio" class="raido-btn" id="coral3" value="coral3" />
<label for="coral3">CORAL III</label>
Here is the Javascript code:
if($('#coral1').prop('checked')){
apartamentos = 'Coral 1';
}
else if($('#coral2').prop('checked')){
apartamentos = 'Coral 2';
}
else if($('#coral3').prop('checked')){
apartamentos = 'Coral 3';
}
I don't know how to set the variable "apartamentos" to the radio button which is checked.
It always set the variable apartamentos = 'Coral'
Thanks in advance
JQuery has a few ways to do this. One way I usually do it is by using .is(), for example, $('#coral2').is(':checked'). You could also use apartamentos = $('.raido-btn:checked').val()
What are you attaching that if statement to? I attached it to the clickevent in jsFiddle and and it seems to be working fine. I'm not sure if you want apartamentos to be set to the value of the radio button or the strings that you defined, but it's definitely being updated.
http://jsfiddle.net/FTT5e

Change an onclick value with javascript

I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
​
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.

Radio button required - JavaScript validation

I know nothing of JavaScript.
I had to add a group of two radio buttons to an HTML form with values "yes" and "no".
Now I need to make them "required"
There are several other required fields in the form and this piece of JavaScript:
<SCRIPT LANGUAGE="JavaScript">
<!--
reqd_fields = new Array();
reqd_fields[0] = "name";
reqd_fields[1] = "title";
reqd_fields[2] = "company";
reqd_fields[3] = "address";
reqd_fields[4] = "city";
reqd_fields[5] = "state";
reqd_fields[6] = "zip";
reqd_fields[7] = "phone";
reqd_fields[8] = "email";
reqd_fields[9] = "employee";
function validate(form_obj) {
if (test_required && !test_required(form_obj)) {
return false;
}
It was done by someone else, not me.
What I did is just added my field to this array, like this:
reqd_fields[10] = "acknowledge";
However it doesn't seem to be working.
Please guide me as I am totally ignorant when it comes to JavaScript.
Why don't you just make one selected by default then one will always be selected.
A link to your page or a sample of your HTML would make this easier, but I'm going to hazard a guess and say that the values in the array match the "name" attribute of your radio button elements.
If this the case, "acknowledge" should be the name of both radio buttons, and to make things easier, one should have the attribute "checked" set to "true" so there is a default, so you'll get a value either way.
So, something like this:
<input type="radio" name="acknowledge" value="yes" /> Yes <br/>
<input type="radio" name="acknowledge" value="no" checked="true" /> No <br/>
I know question is ancient but this is a simple solution that works.
<script type="text/javascript">
function checkForm(formname)
{
if(formname.radiobuttonname.value == '') {
alert("Error: Please select a radio button!");
return false;
}
document.getElementById('submit').value='Please wait..';void(0);
return true;
}
</script>
<form name="formname" onsubmit="return checkForm(this)"
<input type="radio" value="radio1" name="radiobuttonname" style="display:inline;"> Radio 1<br>
<input type="radio" value="radio2" name="radiobuttonname" style="display:inline;"> Radio 2<br>
<input type="submit" value="Submit">
</form>
Without seeing your HTML and more context of your validate function it's unclear exactly what you're looking for, but here's an example of how to require a selected value from a radio group:
<form name="form1">
<input type="radio" name="foo"> Foo1<br/>
<input type="radio" name="foo"> Foo2<br/>
</form>
<script type="text/javascript">
var oneFooIsSelected = function() {
var radios = document.form1.foo, i;
for (i=0; i<radios.length; i++) {
if (radios[i].checked) {
return true;
}
return false;
};
</script>
Here is a working example on jsFiddle.
I always recommend using jQuery validate seems better to me than trying to re-invent the wheel

Categories