Javascript Radio Button Value in URL - javascript

I've read variations on this for a few days and can't find a working solution to what I want. And it's probably easier than I'm making out.
I have a set of radio buttons, and want to pass the checked value to part of a URL.
<input type="radio" name="link" value="one" checked="checked">One
<input type="radio" name="link" value="two">Two
<input type="radio" name="link" value="three">Three
And I want the value of whichever one is checked to be passed to a variable such as
dt which then passes to the Submit button which takes you to a url that includes text from the radio buttons.
<input type="button" value="OK" id="ok_button" onclick="parent.location='/testfolder/' + dt;>
But I'm struggling to find out how to get
var dt = document.getElementByName('link').value;
to work for me when I try and apply a for loop to make sure it's checked.
Does my onclick='parent.location.... in the submit button need to be in a function rather than part of the submit button? So the same function can grab the value of the radio button?
So I'm appealing to StackOverflowers for hopefully a bit of guidance... Thanks

First of you want to know which value your combobox has with this easy to use on-liner.
document.querySelector('[name="link"]:checked').value;
I suggest using event handlers to handle the javascript, so don't write it in the onclick attribute.
var btn = document.getElementById('ok_button');
btn.addEventListener('click', function(){ /*handle validations here*/ })
jsfiddle

you can try below code
<input type="button" value="OK" id="ok_button" onclick="functionName();'>
JavaScript Code
<script type="javascript">
function functionName(){
var radios = document.getElementsByName('link'),
value = '';
for (var i = radios.length; i--;) {
if (radios[i].checked) {
value = radios[i].value;
break;
}
}
window.location.href='/testfolder/'+ value
}
</script>

var dt = document.getElementsByName('link')[0].value works for me
you can use it in either the inline onclick handler or a function you define

<input type="radio" id="1" name="link" onchange="WhatToDo()" value="one">One</input>
<input type="radio" id="2" name="link" onchange="WhatToDo()" value="two">Two</input>
<input type="radio" id="3" name="link" onchange="WhatToDo()" value="three">Three</input>
<script type="text/javascript">
function WhatToDo() {
var rButtons = document.getElementsByName('link');
for (var i = 0; i < rButtons.length; i++) {
if (rButtons[i].checked) {
alert(rButtons[i].value);
}
}
}
</script>
Maybe something like this. Use onchange and then loop through your radio buttons. Whilst looping look to see if the radio button is checked. Its a starting point.

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>

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.

"Check All" function when using Ryan Fait's "Custom Form Elements"

I've made a simple form using Ryan Fait's Custom Form Elements. Now I am trying to implement a "Check All"/"Uncheck All" function.
What I have mostly works, except that the user has to click the buttons twice to get the desired result. I have a feeling that I need to call this function from inside the Custom Form Elements script, but I don't know how.
I'm using JQuery, Custom Form Elements (http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/custom-form-elements.js), and this:
<script type = "text/javascript">
function cboxToggle(group, action) {
for( var i=0, len = group.length; i < len; i++) {
group[i].checked = action;
}
}
</script>
My HTML:
<form name="myname" action="checkboxes.asp" method="post">
<input type = "button" value = " CHECK ALL" onclick = "cboxToggle(check_list, !this.checked)"><br>
<input type = "button" value = " UNCHECK ALL" onclick = "cboxToggle(check_list, this.checked)"><br>
<p><input type="checkbox" name="check_list" value="1" class="styled" />Option 1 </p>
<p><input type="checkbox" name="check_list" value="2" class="styled" />Option 2 </p>
<p><input type="checkbox" name="check_list" value="3" class="styled" />Option 3 </p>
</form>
Any help would be appreciated -- thanks!
If you're using jQuery then why not use it to its full potential? Which also means, no inline code... Add an id to your buttons first. Then make sure you're using groups properly, so instead of group you do group[]. Then use this code and it should work:
var ckToggle = function (group, action) {
$('[name="'+ group +'"]').prop('checked', action)
}
$('#buttonAll').click(function(){ ckToggle('check_list[]', true) })
$('#buttonNone').click(function(){ ckToggle('check_list[]', false) })
Check out the following URL
Uncheck checkbox in custom form elements

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

Trying to find selected radio button. What's wrong?

I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.

Categories