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?
Related
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.
I have a drop down which may or may not change the value of a hidden field. The change is decided by a calculation function.
I want to track the change in the hidden field. If there is any change, I want to check a checkbox.
How can this be achieved?
I cannot change my HTML. Hence everything is has be handled in the JS.
<input type="hidden" name="03Text" value="">
In Java script:
var w = dojo.query('[type$=hidden]');
w.forEach(function(node, index, nodelist){
dojo.connect(node , "onchange", function(evt){
controlapiObj.setControlAttribute(payload.srcFormId, payload.outputParams[0], true, "checked");
});
});
I use dojo.query because there are many such hidden fields in the form, and I have to monitor the value change of all.
*emphasized text*I believe the problem is with the the "onchange" event not firing when you programmatically change the value of the hidden field. You can trigger this event manually the same time the value of the field is changed like so. My example uses dojo 1.10 and the on function
HTML:
<input type="hidden" name="03Text" value="1">
<input type="hidden" name="03Text" value="2">
<input type="hidden" name="03Text" value="3">
SCRIPT:
require(["dojo/query", "dojo/on", "dojo/domReady!"], function(query, on){
var w = query('[type$=hidden]');
w.forEach(function(node, index, nodelist){
on(node, "onchange", function(){
console.log(node);
})
});
var event = new Event('onchange');
w[0].dispatchEvent(event);
w[1].dispatchEvent(event);
w[2].dispatchEvent(event);
})
Jsfiddle with example:
http://jsfiddle.net/kagant15/ay1dzqqg/
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
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"
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.