How to check a Particular Radio Box in a "Group" using JavaScript - javascript

I have a radio box group and I need to select a given radio box using javascript as in the following case, I have to check option with value D3
<input type="radio" name="day" id="day" value="D1" />D1
<input type="radio" name="day" id="day" value="D2" />D2
<input type="radio" name="day" id="day" value="D3" />D3
<input type="radio" name="day" id="day" value="D4" />D4
How can the third option for example be checked?

Be sure putting this radio group in a form and change the theNameOfTheForm to your form's name.
<form name="theNameOfTheForm">
..
..
..
</form>
The java-script function:
<script type="text/javascript">
function select_radio_value(theValue)
{
for (var i=0; i < document.theNameOfTheForm.day.length; i++)
{
if (document.theNameOfTheForm.day[i].value == theValue)
{
document.theNameOfTheForm.day[i].checked = true;
}
}
}
</script>
Now you can use it as a js function on any event. for instance:
<input type='button' name='c3' value='Click Here to check the D3 radio' onClick="javascript:select_radio_value('D3')">

Normally, you'd use document.getElementById('day').val or jQuery('#day').val(). That is, if they have different ids. If they share the id, I'm not sure you can with document.getElementById since it assumes that the ids are different, but perhaps
jQuery('#day')[3].val()
could work, because jQuery actually returns an array of elements that match the criteia

Remove the unique ID from each of the checkboxes. You should only have ONE unique ID on a page.
In JavaScript, access the third checkbox in this group with the following and set it to checked:
var inputs = document.getElementsByTagName('input');
inputs[2].setAttribute('checked', 'checked');
OR, you can simply add checked=checked to your HTML.

function selectRadio(toBeSelectedRadioIndex)
{
var radioElements = document.getElementById('day');
radioElements[toBeSelectedRadioIndex].checked = true;
}
In many cases you need to have Id names different for your elements.
You can then give them same name and use getElementsByTagName instead.
The the code will look like...
function selectRadio(toBeSelectedRadioIndex)
{
var radioElements = document.getElementsByTagName('day');
radioElements[toBeSelectedRadioIndex].checked = true;
}

I would give the radio buttons different ids and then do the following :
d3.select("input#thirdRadio").property("checked", "true");

Related

jquery each() returns all objects as the same

Disclaimer, i am a rookie developer but am learning as i go. I have been working on this one issue for a few days now trying to interpret similar problems but to no avail.
The problem. I generate a list dynamically and each <li> has 4 input fields, 1 select box, and 2 check boxes. Values for each input are populated and the users should be able to modify. On save i am trying to use jquery to loop through the list using each() and return the values so i can push into and array/object ending up with an object for each row with name->value pairs so i can pass with ajax and save the updated input fields.
Here is the code that creates the list. (be gentle with the rookie)
echo'<li id= '.$list[id].' name="clubli" class="club">
<input type="text" name="displayorder" class="clubelement" style=" width:30px; text-align: center;" value="'.$list[display_order].'"; autofocus />
<input type="text" name="clubname" class="clubelement" value="'.$list[club_name].'" /><select id ="clubtype" name="clubtype" class="clubelement" style="width:130px;">
<option selected ="selected">'.$list[club_type].'</option>
<option id = "'.$results1[0]->id.'">'.$results1[0]->club_type.'</option>
<option id = "'.$results1[1]->id.'">'.$results1[1]->club_type.'</option>
<option id = "'.$results1[2]->id.'">'.$results1[2]->club_type.'</option>
<option id = "'.$results1[3]->id.'">'.$results1[3]->club_type.'</option>
<option id = "'.$results1[4]->id.'">'.$results1[4]->club_type.'</option>
<option id = "'.$results1[5]->id.'">'.$results1[5]->club_type.'</option>
</select>
<input style="text-align: center; width: 40px"; type="text" name="clubdist" class="clubelement" value= "'.$list[range_distance].'" /></option>
<input type="checkbox"; name="inactive"; class="clubelement"; '.$active.' /><input type=checkbox name="remove" class="clubelement"; />
<div style="margin-bottom:1em"></div></li>';
When user selects save button a JS is called which is as follows:
<script src="https://ajax.googleapis.com/ajax/libs/ jquery/1.12.0 /jquery.min.js"></script><script type="text/javascript">
function saveClubs() {
$userclubs = [];
$('.clubslist li').each(function(i) {
$id=$("[name='clubli']").attr('id');
$displayorder= $("[name='displayorder']").val();
$clubname= $("[name='clubname']").val();
$clubtype= $("[name='clubtype']").val();
$clubdist= $("[name='clubdist']").val();
$clubinactive= $("[name='inactive']").is(":checked");
$clubremove= $("[name='remove']").is(":checked");
$userclubs.push({'id':$id, 'displayorder':$displayorder, 'clubname':$clubname, 'clubtype':$clubtype, 'clubdist':$clubdist, 'inactive':$clubinactive, 'remove':$clubremove});
});
console.log($userclubs);
The console log show a result of "object" "object" "object" "object" which is expected as there are 4 rows to the list. However each object as the same 7 inputs in them - all the first row of the list. I understand that the loop is reading the first row everytime even though it is loops the expected number of times. Any guidance would be greatly appreciated....
You are close, they query selectors (e.g. $displayorder= $("[name='displayorder']").val();) are going to match the first value. So for each iteration of the loop, you only get the first matched DOM element.
To fix that, you'd need to reference the DOM element that the each() loop is currently iterating over. Something like this would work:
function saveClubs() {
$userclubs = [];
$('.clubslist li').each(function(i) {
$id=$(this).attr('id');
$displayorder= $(this).find("[name='displayorder']").val();
$clubname= $(this).find("[name='clubname']").val();
$clubtype= $(this).find("[name='clubtype']").val();
$clubdist= $(this).find("[name='clubdist']").val();
$clubinactive= $(this).find("[name='inactive']").is(":checked");
$clubremove= $(this).find("[name='remove']").is(":checked");
$userclubs.push({'id':$id, 'displayorder':$displayorder, 'clubname':$clubname, 'clubtype':$clubtype, 'clubdist':$clubdist, 'inactive':$clubinactive, 'remove':$clubremove});
});
}
Here is an example in a JS Fiddle, where you can see it working with some test data based on your PHP: https://jsfiddle.net/qg063zaL/
Hope that helps! :-)

is there a defaultValue property for radio select?

I am wondering if there is a way to reset a radio to it's originally selected option. I know of defaultValue for inputs but is there a way to make it so that I can reset the radios back to their originally selected value on page load?
I am not wanting to simply unselect all radios. I am trying to put them back to their originally selected value.
Thanks for any info.
Yes, radio inputs do have defaultValue property, but what you are looking for is the defaultChecked property:
$('input[type=radio]').prop('checked', function() {
return this.defaultChecked;
});
That being said, if you want to reset the form you can use the reset method of the HTMLFormElement object:
$('#formElement').get(0).reset();
I think you want this
<form action="">
<input type="radio" name="gender" value="male" checked="true"/>Male
<input type="radio" name="gender" value="female"/>Female
<input type="reset" value="reset"/>
</form>
Any time you will reset the form, the male radio button will be selected.
I will rather make a jQuery plugin like this:
$.fn.defaultVal = function (checked) {
if(checked === true || checked === false) {
$(this).attr("data-default", checked);
return;
}
if(!$(this).attr("data-default")) {
console.log("No default value assigned!");
return;
}
return $(this).attr("data-default");
}
JSFIDDLE LINK UPDATE
Working Demo is here: JSFIDDLE

Length is returning undefined but value is showing

I have a function where I get an error saying "length" is null, I then did an alert to see the value and length and I see that the value is coming back in the loop, sometimes it has a String value and sometimes it has a number (eg. SUIT and then 8), but for some reason the length is showing as undefined? The radioobj variable takes radio button values that are coming in from the form input.
function getRadioValue(radioobj) {
radiovalue = "";
for (i=0, n=radioobj.length; i<n; i++) {
if (radioobj[i].checked) {
radiovalue = radioobj[i].value;
break;
}
}
if (!radiovalue) { return 0; }
else { return radiovalue; }
}
The way the code is written, it appears to be looking to take in a group of radio buttons and looping through them to find the one that is checked. To do that, the input MUST be a collection of radio buttons . . . passing an individual reference to a radio button will not work (and will give an undefined value for radioobj.length). Example:
HTML
<fieldset id="radioVals">
<input type="radio" name="radioVals" id="val0" value="">Pick an value . . .</input>
<input type="radio" name="radioVals" id="val1" value="Value1">Value 1</input>
<input type="radio" name="radioVals" id="val2" value="Value1">Value 2</input>
</fieldset>
Given this group, if you were to pass in a reference to any of the individual radio buttons (e.g., using document.getElementById), you will get and error, because what is returned by that method is the reference to an individual element.
var radioOption = document.getElementById("val0");
window.console.log(radioOption.length); // will log "undefined"
However, if you pass in an array of radio button elements (e.g., using .children), you can use the for loop, because the array will have a length.
var radioOptions = document.getElementById("radioVals").children;
window.console.log(radioOptions.length); // will log "3"
From what you are describing, it sounds like the code is using the first approach, rather than the second. There are certainly ways of doing this check with individual radio buttons, but that is not how this code has been set up.
You can get collection of radios with the same id easily.
Use for it document.forms['form_id']['radio_id']:
<form id="form_id">
<input type="radio" name="radio_name" id="radio_id" value="Value1" />Value 1
<input type="radio" name="radio_name" id="radio_id" value="Value2" />Value 2
<input type="radio" name="radio_name" id="radio_id" value="Value3" />Value 3
</form>
var radio_list = document.forms['form_id']['radio_id'];
alert(radio_list.lengh) // will "3"

Using prepopulated form, submit only changed fields

I have an html form that uses select and text inputs. The form comes pre-populated with default values. How can I submit only the inputs that were changed by the user from their default values? Note that this page is to be stored in an embedded system with limited space, so using a javascript library is out of the question.
Example html:
<form>
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<select name="field3">
<option value="option1" select>Option 1</option>
<option value="option2" select>Option 2</option>
</select>
<input type="Submit" />
</form>
To be clear, inputs that the user does not change should not show up in the POST request when the form is submitted.
As per Barmar's suggestion to use an array to track which values have changed, this is the solution I have come up with and it works.
Here is the js:
var tosubmit = []
function add(name) {
if(tosubmit.indexOf(name) == -1)
tosubmit.push(name);
}
function is_changed(name) {
for(var k = 0; k < tosubmit.length; k++)
if(name == tosubmit[k])
return name && true;
return false;
}
function before_submit() {
var allInputs = document.getElementsByTagName("input");
var allSelects = document.getElementsByTagName("select");
for(var k = 0; k < allInputs.length; k++) {
var name = allInputs[k].name;
if(!is_changed(name))
allInputs[k].disabled = true;
}
for(var k = 0; k < allSelects.length; k++) {
var name = allSelects[k].name;
if(!is_changed(name))
allSelects[k].disabled = true;
}
}
html:
<form onSubmit="beforeSubmit()">
<input type="text" name="field1" value="value1" onchange="add('field1')" />
<input type="text" name="field2" value="value2" onchange="add('field2')" />
<select name="field3" onchange="add('field3')">
<option value="option1" select>Option 1</option>
<option value="option2" select>Option 2</option>
</select>
<input type="Submit" />
</form>
This works because form elements that are disabled are not included in the POST Request. Thanks everyone for their suggestions.
If you can use HTML5, you can use the placeholder attribute, example. Keep in mind this won't work with older browsers like IE6-8.
<form>
<input type="text" placeholder="placeholder text" name="field1" value="" />
<input type="Submit" />
</form>
If you can't use that, you'll have to do a detect on form submit with javascript and check the value of the objects your submitting. The other option is to have a label of your preview text and hide it when input boxes are selected or contain a value that isn't empty.
waldol1's method works. Here I'm making a suggestion, and offering an alternate way.
Improvement:
For cleaner code, just use "add(this)" for each input element.
<input onchange="add(this)" />
Then, in the add() function, just add one more line to get the name of the element being clicked
function add(e) {
var name = e.name;
// do stuff
}
Alternate solution:
I'm not submitting a form the classic way; I'm just using input elements and doing stuff with Javascript. I don't care about disabling form elements, and don't want to rely on that as a flag. Instead I'm using a JS object to store my changed variables, then I just run through the object when I build my parameters (in my case, to submit via AJAX request).
Define a global "tosubmit" object (you could use an array if you want).
var tosubmit = new Object();
For any input element I want updateable, I call add(this) when there's a change:
<input onchange="add(this)" />
The JS function adds the changed element to my temporary storage object.
function add(e) {
// Store the element and it's value, ready for use later.
tosubmit[e.name] = e.value;
}
When I'm ready, I build parameters for my AJAX update. In my casI run the function with an ID, in my case. I run through the tosubmit object, and if the update is successful, I clear it out, ready for another use.
function sendUpdate(id) {
// Start building up my parameters to submit via AJAX to server.
var params = "id="+encodeURIComponent(id);
// Run through the tosubmit object, add any updated form elements.
for (var i in tosubmit) {
params = params + "&" + i + "=" + encodeURIComponent(tosubmit[i]);
}
// (Do other stuff, build my http request, etc)
// Eventually submit params with the http request
http.send(params);
}

How to iterate through all checkboxes on the page?

How do I can iterate through all checkboxes on the page with JQuery?
I.e. I have those checkboxes above...
<div>
<input checked="checked" type="checkbox" name="option_1" id="checkbox_1" value="1" />35 MM
<input checked="checked" type="checkbox" name="option_2" id="checkbox_2" value="2" /> DIGITAL
<input type="checkbox" name="option_3" id="checkbox_3" value="3" /> 3D DIGITAL
</div>
Have I use
$('input[id^="checkbox_"]').each(function() {
});
Is it correct? Thank you!
$("input[type='checkbox']").each(function(){
var name = $(this).attr('name'); // grab name of original
var value = $(this).attr('value'); // grab value of original
var ischecked = $(this).is(":checked"); //check if checked
});
You can use this to iterate through the checkboxes:
$("input:checkbox").each(function() {
alert($(this).val());
});
jQuery supports a selector :checkbox that is just for selecting checkboxes on the page so if you want all checkboxes on the page that's the simplest way to do it:
$(":checkbox").each(function(index, element) {
// put your code here
});
In the jQuery doc for :checked, they recommend that this selector might perform slightly faster:
$("input[type='checkbox']").each(function(index, element) {
// put your code here
});
$('input[type="checkbox"]').each(function() {
...
});
It seem alright but you can add further type check to ensure not other control type with mataching id comes in selector.
$('input[type=checkbox][id^="checkbox_"]').each(function() {
});

Categories

Resources