How to retrieve the value from a radio button in javascript? - javascript

Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.

This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference

Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
​function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
​
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.

function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/

You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".

Related

Jquery one button updates multiple input fields on form

I am trying to update two input fields in a form when clicking one button. I actually had all the code right when using document.getElementById, but the form that I'm using strips the ID's I set away, so I can't use getbyid. If I know the form field name, how could I change my function to do the same thing? Please note that my form has more than two fields, including a submit button, so I don't want to update those.
This is what I used before (with the ID selector)
Html:
<input type="text" name="field-1" id="info1">
<input type="text" name="field" id="info2">
Populate
JS:
function addTxt(val, id,no)
{
var id = id;
for(var i=1;i<=no;i++){
document.getElementById(id+i).value = val[i-1];
}
}
Fiddle:
http://jsfiddle.net/qwz47phx/3/
Edited with a much simpler and readable approach
function addVal(obj) {
event.preventDefault(); // Prevent page scrolltop on anchor click
$.each(obj, function(k, v) {
$("input[name='"+ k +"']").val( v );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo">
<input type="text" name="bar">
<a href="#" onclick='addVal({foo:"Hello", "bar-baz":"World"})'>Populate</a>
Or with native JS (ES5+):
function addVal(obj) {
Object.keys(obj).forEach(function(name) {
document.querySelector('input[name="' + name + '"]').value = obj[name];
});
}
<input type="text" name="foo">
<input type="text" name="bar">
<input type="text" name="name-with-dashes">
<a href="#" onclick='addVal({foo:"Hello", bar:"World", "name-with-dashes": "Works !"})'>Populate</a>
If you have problems with IDs you can use querySelector to select inputs by name like this:
JS:
function addTxt(val, id, no) {
for (var i = 1; i <= no; i++) {
document.querySelector('input[name="' + id + i + '"]').value = val[i - 1];
}
}
HTML:
<input type="text" name="info1" id="info1">
<input type="text" name="info2" id="info2">
Populate
Demo: http://jsfiddle.net/iRbouh/qwz47phx/6/
I hope this will help you.
You can use a jQuery attribute= selector to grab by name instead of ID.
function addTxt(val, id,no)
{
for(var i=1;i<=no;i++){
var name = id+i;
$("input[name='"+name+"']").val(val[i-1]);
}
}
Please note that this function will be looking for names of info1, info2, info3, etc, just as your original script did. However, in the HTML, you have names of info and info-1. Either the names will have to be changed to fit the function, or the function can be slightly more intricate.
Fiddle: http://jsfiddle.net/qwz47phx/8/

How to manipulate individual input field values without a lot of code

I wrote some code using jQuery to convert <input> field values from one unit system to another (English <-> Metric). All was going well until I have realized that I am using a class selector, so instead of each value doing its conversion individually, all values (with same class) get converted to the same identical value (equal to the first occurrence of class).
An obvious solution is to assign an id to each value, which I suppose will work, but I am here to ask if there is a better way. I have a lot of values (which is why I tried using class), and would like to avoid using id, if possible. But, all I am looking for is "convert each value individually (using my conversion function)". How can this be done?
jQuery
function convertValues() {
if ($('#unit_system').val() == "English") //if changed to English
{
$('.value_gpm').val( //do converstion from Metric to English
convert($('.value_gpm').val(), "m3h", "gpm")
);
}
else if ($('#unit_system').val() == "Metric") //if changed to Metric
{
$('.value_gpm').val( //do conversion from English to Metric
convert($('.value_gpm').val(), "gpm", "m3h")
);
}
}
Calling Function
//below code is for select box (HTML for it is not shown)
$("#unit_system").change(function(){ //select box change detected
convertValues(); //function is called
});
HTML at first (before Select box change)
<input type="text" class="value_gpm" name="design_a" value="444" />
<input type="text" class="value_gpm" name="design_b" value="555" />
<input type="text" class="value_gpm" name="design_c" value="666" />
<input type="text" class="value_gpm" name="design_d" value="777" />
<input type="text" class="value_gpm" name="design_e" value="888" />
HTML after (after Select box is changed)
<input type="text" class="value_gpm" name="design_a" value="1954.87" />
<input type="text" class="value_gpm" name="design_b" value="1954.87" />
<input type="text" class="value_gpm" name="design_c" value="1954.87" />
<input type="text" class="value_gpm" name="design_d" value="1954.87" />
<input type="text" class="value_gpm" name="design_e" value="1954.87" />
Expected behavior: conversion produces different value per row
Actual behavior: same value produced for each row
Just loop through them, something like this.
var inputs = $('.value_gpm');
for(i=0;i < inputs.length; i++){
var input = inputs[i];
input.val( convert(input.val(), "m3h", "gpm") );
}
Best bet - using $.each and $(this).
$(document).ready(function(){
var valueEls = $('.value_gpm');
$("#unit_system").change(function(){
var unit = $(this).val();
switch(unit){
case "English":
valueEls.each(function(){
$(this).val(convert($(this).val(), "m3h", "gpm");
});
break;
case "Metric":
valueEls.each(function(){
$(this).val(convert($(this).val(), "gpm", "m3h");
});
break;
}
});
});
Use each()
$("value_gpm").each(function () {
convert(this.val(), ...etc
The less lines of codes I figure out for this is this:
var unit_system = $('#unit_system').val();
$('.value_gpm').each(function(){
convert($(this).val(), unit_system == "English" ? "m3h" : "gpm", unit_system == "English" ? "gpm" : "m3h");
});
You can use jQuery each:
$("#unit_system").change(function(){
var fromUnit = "m3h";
var toUnit = "gpm";
if ($(this).val() == "Metric"){
fromUnit = "gpm";
toUnit = "m3h";
}
$('.value_gpm').each(function(){
$(this).val(convert($(this).val(), fromUnit, toUnit));
});
});

Looping through checkboxes with javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server to saved in a table. I have tried the below code:
<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>
<script>
$('#save-btn').click(function(evt){
evt.preventDefault();
var numberOfChBox = $('.publish').length;
var checkArray = new Array();
for(i = 1; i <= numberOfChBox; i++) {
if($('#chkBox' + i).is(':checked')) {
checkArray[i] = 1;
} else {
checkArray[i] = 0;
}
}
alert(checkArray);
});
</script>
but the alert outputs this:
,1,0,1,0,1,1
The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?
Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/
Pretty good link: https://learn.jquery.com/javascript-101/arrays/
Also in your html end your tag /> i.e.
<input class="publish" id="chkBox4" type="checkbox" checked>
rest should help :)
Code
var checkArray = new Array();
$('input[type=checkbox]').each(function () {
this.checked ? checkArray.push("1") : checkArray.push("0");
});
alert(checkArray);
As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?
var checkArray = [];
$('input.publish').each(function () {
checkArray.push($(this).is(':checked'));
});
alert(checkArray);
Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].
Replace checkArray[i] with checkArray[i-1] inside the for bucle

How to get value from form input type=radio?

<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>
and js:
var type = this.type.value;
alert(type);
How to fix it ?
In what context does that JS code run? If this is the radio button in question then this.value will return the value.
If your question is "How do I get the value of the currently selected radio button in the 'type' group?" then you may need to do something like this:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
for (i=0; i < rads.length; i++)
if (rads[i].checked)
return rads[i].value;
return null; // or undefined, or your preferred default for none checked
}
var checkedValue = getCheckedRadioValue("type");
(It would be easier with .querySelector() or .querySelectorAll(), but not all browsers support them.)
Just use selectors.
With jquery
$("input[name=type]:checked").val();
Or without jquery:
document.querySelector("input[name=type]:checked").value;
Just use this.value instead of this.type.value.
this.value will select the value associated with the value attribute of the input. (That's a mouthful).
Using jQuery you can do like this
$(function() {
$(".rad").click(
function() {
alert(this.value);
});
});
See this JSFiddle

creating a for-loop using Javascript?

I have a problem creating a for-loop using Javascript. It seems everyting is fine for me but still I didn't get what I want.
Take a look please to this code to understand more:
The HTML form code:
<form name="myform">
<textarea name="inputtext" cols="100%" rows="10%"></textarea><br />
<input type="radio" name="options" value="javascript" checked> Option1 <br />
<input type="radio" name="options" value="windows"> Option2<br />
<input type="button" value="Do it" onClick="generate();"><br />
<textarea name="outputtext" cols="100%" rows="10%"></textarea><br />
</form>
The Javascript code:
function generate() {
var code = ""+document.myform.inputtext.value;
if (document.myform.options[0].checked) {
document.myform.outputtext.value = escape(code);
}
else {
var result= "2- ";
for(int i=0; i<code.length; i++) {
//There will be some logic to decide if to add the char or not.
result+=code.charAt(i);
}
document.myform.outputtext.value = result;
}
}
The problem is not clear for me.
However, when I try to comment out the for-loop, everything works fine !
Any ideas?
There is no int data type in Javascript (or any data types at all used to declare variables).
for(var i=0; i<code.length; i++) {
There is also an Object-oriented solution to this.
var generate = {
loop: function() {
var code = ""+document.myform.inputtext.value;
if (document.myform.options[0].checked) {
document.myform.outputtext.value = escape(code);
}
else {
var result= "2- ";
//CHANGE THE INT(I assume Java) DATATYPE TO A LOCAL VARIABLE USING THE var KEYWORD TO KEEP THE SCOPE IN THE FOR LOOP
//RECURSION CAN BE QUICKER
for(var i=0; i<code.length; i++) {
//There will be some logic to decide if to add the char or not.
result+=code.charAt(i);
}
document.myform.outputtext.value = result;
}
}
generate.loop();

Categories

Resources