is there a defaultValue property for radio select? - javascript

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

Related

Auto-Select Radio Button By Default And Execute 'onchange' Function

I've achieved the first part of the question using php or js. I use php to echo checked attribute. The problem here is that the radio inputs have other inputs that become visible upon selection with onchange event. However, if any of the radio gets selected/checked by default, the conditional inputs aren't displayed until I change the radio selections. Hence the question, how do I get it checked by default and still have the respective conditional inputs displayed.
<input name="mode" id="single" onchange="conditionalDisplay(this.value)" type="radio" value="single" <?php if($mode == single){echo 'checked';}>
<input name="mode" id="multi" onchange="conditionalDisplay(this.value)" type="radio" value="multi" <?php if($mode == multi){echo 'checked';}>
When single is selected, other inputs become visible. Same goes for multi. If the condition specified in the php code is true, then one of them gets selected/checked by default but the accompanying hidden inputs from the onchange function are not displayed until the selection is changed.
N:B - The value of $mode is retrieved from a database.
You can trigger onchange programmatically, for ex., with element.onchange();.
function conditionalDisplay(value) {
// Let's for example log to browser console
console.log('Do something useful with ' + value);
}
// When DOM is ready, trigger an `onchange` event
document.addEventListener('DOMContentLoaded', function() {
var singleElement = document.getElementById('single');
var multiElement = document.getElementById('multi');
// Test which exactly element is checked
console.log(`singleElement.checked: ${singleElement.checked}`);
console.log(`multiElement.checked: ${multiElement.checked}`);
if (singleElement.checked == true) {
singleElement.onchange();
} else {
multiElement.onchange();
}
});
<input name="mode" id="single" onchange="conditionalDisplay(this.value)" type="radio" value="single">
<input name="mode" id="multi" onchange="conditionalDisplay(this.value)" type="radio" value="multi" checked>
This one might be useful for you as well How can I trigger an onchange event manually?

Check for checkboxes in form and get attribute instead if value

I have a form which is saved to Local Storage as a String. My form however has few checkboxes, radio buttons and so on that use attribute instead of value. How can I perform such a check and pass on right "values" to the Local Storage in my dataSave function?
function dataSave(){
var mngrFields = {};
$(".mngr-field").each(function(){
if ($(".mngr-field").is("checkbox")){
mngrFields[this.id] = this.attr("checked");
} else {
// Default method to get input-text values
mngrFields[this.id] = this.value;
}
});
localStorage.setItem('fieldString', JSON.stringify(mngrFields));
}
The default method to get input-text values is working just fine on it's own, but when the checkbox checker is included, it breaks the whole application because of an error.
Any ideas on how can I build up a good checker that I might be able to use for radio buttons as well?
In general all you need to do is just to check the type of input fields and to detect checked attribute for radio and checkbox ones - both of them have true/false for it. Here is the example with all basic HTML types:
<input class="mngr-field" type="radio" id="field-01" checked> Checked radio<br>
<input class="mngr-field" type="radio" id="field-02"> Unchecked radio<br>
<input class="mngr-field" type="checkbox" id="field-03" checked> Checked checkbox<br>
<input class="mngr-field" type="text" id="field-04"> Comment on how it went?<br>
<select class="mngr-field" id="field-05">
<option value="">Rate</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select> Rate it<br>
<textarea class="mngr-field" id="field-06">Area text</textarea><br>
<input type="button" value="Save to LS" onclick="dataSave()">
<script>
function dataSave() {
var mngrFields = {};
$('.mngr-field').each(function () {
if(this.type == 'radio' || this.type =='checkbox')
mngrFields[this.id] = this.checked;
else
mngrFields[this.id] = this.value;
});
localStorage.setItem('fieldString', JSON.stringify(mngrFields));
console.log(JSON.parse(localStorage.getItem('fieldString')));
}
</script>
Console log output:
Object {field-01: true, field-02: false, field-03: true, field-04: "Input text", field-05: "2", "field-06":"Area text"}
field-01: true
field-02: false
field-03: true
field-04: "Input text"
field-05: "2"
field-06: "Area text"
I'm sure you know how to proceed with localStorage string after that. :)
It seems this line if ($(".mngr-field").is("checkbox")){ is the culprit. jQuery is checks for the conformance of an element with a selector, and "checkbox" does not seem to be a valid selector for a checkbox. Try if ($(".mngr-field").is(":checkbox")){ instead.

Set Checkbox when Radio button changes with Knockout

I am new to knockout and I have an issue that has stumped me so far. I have spent a whole day on this with little progress.
I have 4 radio buttons that are bound to an observable called InvType:
<input type="radio" id="rdoAIP" name="rdoAIP" value="AIP" data-bind="checked: InvType" />AIP
<input type="radio" id="rdoPSI" name="rdoPSI" value="PSI" data-bind="checked: InvType" />PSI
<input type="radio" id="rdoPSIAIP" name="rdoPSIAIP" value="PSIAIP" data-bind="checked: InvType" />PSI/AIP
<input type="radio" id="rdoShortForm" name="rdoShortForm" value="PSIShortForm" data-bind="checked: InvType" />PSI Short Form
I have several checkboxes that should only be checked when a specific radio button is checked:
<input data-bind="checked: OptionalValue1" id="chk1" type="checkbox" /> Checkbox 1<br/>
<input data-bind="checked: OptionalValue2" id="chk2" type="checkbox" /> Checkbox 2<br/>
<input data-bind="checked: OptionalValue2" id="chk3" type="checkbox" /> Checkbox 3<br/>
When the user clicks a different radio button, a different combination of check boxes should become checked as well. For example, if the "AIP" radio button is checked on initial page load, then the first 2 checkboxes should also be checked. But when the user clicks the "PSI" radio button, then I want only the first checkbox to be checked and the others should be unchecked.
edit:
Sorry but I was not clear about the check boxes. So here are the conditions:
On initial page load, the radio button gets set and this causes the checkboxes to update accordingly. Each different radio value cause a different combination of the checkboxes to become checked and unchecked.
After the page loads, the user can click on an individual checkbox and change its value. This will NOT affect any other checkbox or radio button.
My knockout code so far:
<script type="text/javascript">
var psiInvestigationViewModel = #Html.Raw(New JavaScriptSerializer().Serialize(Model));
function PSIInvestigationViewModel(data)
{
var self = this;
InvestigationType : ko.observable();
ko.mapping.fromJS(data, {}, self);
};
$(function ()
{
ko.applyBindings(new PSIInvestigationViewModel(psiInvestigationViewModel), $('#PSIInvestigation#(ViewData("UniqueID"))')[0]);
});
If someone could show me the code needed to get my checkboxes to update based on the radio button change, then I would be grateful.
Thanks
First, all radio buttons should have the same, so if you select one the other will be deselected.
If the checkboxes are not readonly you can code the selection logic in an init function.
This init function will be called on each radio buttons change :
var VM = function () {
var self = this;
self.InvType = ko.observable();
var initState = function () {
var t = self.InvType();
self.OptionalValue1(t == 'AIP' || t == 'PSIAIP');
self.OptionalValue2(t == 'PSI' || t == 'PSIAIP');
self.OptionalValue3(t == 'PSIAIP');
};
self.OptionalValue1 = ko.observable();
self.OptionalValue2 = ko.observable();
self.OptionalValue3 = ko.observable();
self.InvType.subscribe(initState);
}
ko.applyBindings(new VM());
See fiddle
I hope it helps.
Another way to do it would be to use computed observables:
self.Optionalvalue1 = ko.computed(function() {
return self.InvType() == 'AIP' || self.InvType() =='PSIAIP';
)};
and so on.

condition for input field and checkbox

how can i create a condition for multiple checkbox!
Input Field ID =" INsrvOtr "
CheckBox ID = "INsrv"
let's say that the that the user has two options,either put a value on the input field or choose any value from the checkbox but he can only choose "ONE" of the two options
Checkbox:
<input id="INsrv" name="INopt" type="checkbox" value="1" />1<br>
Input field:
<input id="OUTsrvOtr" name="OUToptOtr" type="text" value="" onblur="valINP()"/><br><br>
if the user inputs a value in the input field this will happen
if "input field" is not empty, class of all the "checkbox" will not contain a value.
<script>
function valINP(){
$("#INsrv1").prop('class','text')
$("#INsrvOtr").prop('class','validate[required] text-input text')
}
}
</script>
or if the user chooses to check the checkbox this will happen
and if the "checkbox" is not selected,class of "input field" will not contain a value.
<script>
$(document).ready(function() {
$("input[name$='INopt']").click(function() {
$("#INsrv1").prop('class','validate[minCheckbox[1]] checkbox text')
$("#INsrvOtr").prop('class','text')
});
});
</script>
or if both is not selected
the script will contain this two:
$("#INsrv").prop('class','validate[minCheckbox[1]] checkbox text')
$("#INsrvOtr").prop('class','validate[required] text-input text')
try optimize your code, some useful optimization for selecting controls
http://api.jquery.com/category/selectors/ or http://api.jquery.com/attribute-contains-prefix-selector/
using some thing like
$("#id|="INsrv"]').prop('class','')
sorry if the syntax goes wrong.
// Use this for INsrv([0-9]+)
$('[id^="INsrv"][id!="INsrvOtr"]').each(function() {
});
// Or if you only want to call `prop`
$('[id^="INsrv"][id!="INsrvOtr"]').prop('yourprop', '');
Then you can just call $('#INsrvOtr') separately.

How to check a Particular Radio Box in a "Group" using 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");

Categories

Resources