Radio button on/off trigger works only one way - javascript

So this is the dumbest thing I've struggled with in awhile. I cannot get the state of a simple radio button set to toggle something on the page.
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" id="completeSw" name="completeSw" value="0" checked="checked"/>No<br/>
So you can see here an extremely simple yes/no radio button set to toggle an action. It needs to serve two purposes: to flag a yes/no value (1/0) in the POST data, and ideally trigger an action on the page using JS/jQuery. I'm having trouble with the latter.
The default state is "No"; if I click "Yes" I can retrieve an onchange or onclick event state and make something happen. However, this is a one-way switch; I cannot retrieve a state going back to the "No" selector once I've gone to "Yes". What I need to be able to do is show / hide an element on the page depending on what choice they've made in this radio set. If I click "Yes", I can trigger the action and see the page change. Once I click "No", however, it acts as if there was no state change and I cannot perform an action i.e. hide the element again.
I've tried variations on retrieving the "checked" state, the radio pair value, etc, e.g.
$("#completeSw").change(function(e){
alert( $(this).attr("checked") ); // only triggers when "Yes" is selected
});
Perhaps I should not be using a yes/no radio pair, but instead be using a single checkbox? Seems more user-friendly and elegant this way (radio buttons) to me.

IDs must be unique, so it will only ever find the first one on your page. Use a class instead.

Really, ID's must be unique, but you don't need 2 ID's. You'll only monitor changes in one radio. For example - "Yes" value
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" name="completeSw" value="0" checked="checked"/>No<br/>
And the you'll process the checked attribute of only this element. True - "Yes", False - "No"

Some browsers don't do anything when alert(message), message=null. And since an unchecked field has no checked-attribute, that could be the thing :).
Try:
alert('Checked: '+$(this).attr("checked"));

This is separate, but you're kinda using the label wrong also. The label is meant to extend the click area so someone could click on the word 'Yes' and the radio button will activate. Hopefully this helps you out a little.
<span>Completed?</span>
<input type="radio" id="completeSwYes" name="completeSw" value="1"/><label for="completeSwYes">Yes</label>
<input type="radio" id="completeSwNo" name="completeSw" value="0" checked="checked"/><label for="completeSwNo">No</label><br/>
<script type="text/javascript" charset="utf-8">
// If the radio button value is one then this evaluates to true.
var completeSW;
jQuery("input[type='radio'][name='completeSw']").change(function() {
completeSW = (jQuery(this).val() == 1);
alert("completeSW checked? " + completeSW);
});
</script>

Related

Check a radio button with javascript

For some reason, I can't seem to figure this out.
I have some radio buttons in my html which toggles categories:
<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.
I have tried versions of this (with and without jQuery):
document.getElementById('#_1234').checked = true;
But it doesn't seem to update. I need it to visibly update so the user can see it.
Can anybody help?
EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().
Do not mix CSS/JQuery syntax (# for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().
Today, in the year 2016, it is safe to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):
document.querySelector("input[name=main-categories]:checked").value
Easiest way would probably be with jQuery, as follows:
$(document).ready(function(){
$("#_1234").attr("checked","checked");
})
This adds a new attribute "checked" (which in HTML does not need a value).
Just remember to include the jQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
By using document.getElementById() function you don't have to pass # before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo:
JSFiddle
I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:
var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
if (response["reload_mode"] == "Periodic") {
document.querySelector('input[name=reload_mode][value="Periodic"]').click();
} else if (response["reload_mode"] == "Page Bottom") {
document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
} else {
document.querySelector('input[name=reload_mode][value="Both"]').click();
}
});
Where the associated code to SAVE the value was:
reload_mode: document.querySelector('input[name=reload_mode]:checked').value
Given HTML like the following:
<input type="radio" id="periodic" name="reload_mode" value="Periodic">
<label for="periodic">Periodic</label><br>
<input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
<label for="bottom">Page Bottom</label><br>
<input type="radio" id="both" name="reload_mode" value="Both">
<label for="both">Both</label></br></br>
It seems the item.checked property of a HTML radio button cannot be changed with JavaScript in Internet Explorer, or in some older browsers.
I also tried setting the "checked" attribute, using:
item.setAttribute("checked", ""); I know the property can be set by default,
but I need just to change the checked attribute at runtime.
As a workarround, I found another method, which could be working. I had called the item.click(); method of a radio button. And the control has been selected. But the control must be already added to the HTML document, in order to receive the click event.

Angularjs radio buttons

I know that this has been spoken about in some Google Threads but I still can't find the right solution to bind my radio inputs to a model (in clean'n simple manner),
Currently I have HTML:
<input ng-model="searchByRma" type="radio" name="search-type">
<input ng-model="searchByDelivery" type="radio" name="search-type">
And in Controller:
$scope.searchByRma = true;
$scope.searchByDelivery = false;
This does not work (as it would with the checkboxes)...
Any ideas on how to set the default value on the first radio button without loosing data-binding?
Thanks!
I think you should use same variable with different values in those
two radio buttons.
<input ng-model="searchBy" value="Rma" type="radio" name="search-type">
<input ng-model="searchBy" value="Delivery" type="radio" name="search-type">
Then, you should have searchBy set either "Rma" or "Delivery" depending on
user input.
What has worked for me is to set the model variable to { } and that will reset the radio buttons to their default (not selected) state. Of course, this will only work if you have your radio button tags correct as in tosh's answer.
In your case:
$scope.searchBy = { };

JQuery, Show / hide a div based on dynamic radio buttons aka radio34 etc?

I'm producing a page dynamically and I have several sets of radio buttons. I need to use the record id in the id tag of the radio buttons. e.g.
<input type="radio" name="review_flag1797" id="review_flag1797"
value="n" checked="checked" />
How can I produce a single JQuery function to handle showing / hiding of my div. My radio buttons will have three values y, n and r. When the value is n I need to hide my div and show it for y and r.
To further complicate this, the radio of the radio button can set to a different value when its written.
EDIT
<div id="my_content1797">
content
</div>
I suggest you use a data-* attribute to store the ID of the set, just to make life a bit easier, maybe also give those radio buttons a common class:
<input ... class="someClass" ... data-id="1797" ... />
Then all you have to do is:
$('.someClass').change(function() {
if(this.checked) {
$('#my_content' + $(this).data('id')).toggle(this.value !== 'n');
}
});
I believe you want the jQuery toggle() method.
http://api.jquery.com/toggle/
onclick="$('#my_content<%=record_id%>').toggle(this.checked);"
You can hide the parent div using this statement
$("input[value='n']").parent().hide();
To show, give
$("input[value!='n']").parent().show();
You have to give this after the statements that add radio buttons dynamically, and also in the change handler of radio inputs. You can put these statements in a function and invoke it.
Also try http://api.jquery.com/closest/ if the div is not parent. This also selects parent.
$("input[value='n']").closest(...).hide();

Having two forms which contain the same radio button group inside them?

My first question is this although I doubt if it is possible. However, if it is, it will make my life much easier.
Can you have a radio button group with 2 forms? What I mean is that the same radio button group is found in both form1 and form2.
The reason why I need this is to that if I click on the first 2 radio buttons, the form action will be to one page, while if I click on the last 2 radio buttons, the action will be to another page.
If this is not possible, I would use one form and will have to change the form action depending on which radio button I select. I will give a class to the first two radio buttons and another class to the other 2 radio buttons.
If anyone can let me know which method is better and how to implement it in jQuery, that would be great.
Many thanks in advance
You cannot have a single group of form elements be part of two separate forms. It's just not possible to construct a valid document like that.
Javascript that dynamically updates the URL in the "action" property of the parent <form> should not be too hard to do. As you suggested, the "class" attribute of the radio button elements can be used to guide the code, making it pretty flexible if you need to add one or more buttons later on.
Since you included the jQuery tag:
$(function() {
var actionMap = {
key1: 'http://yoursite.com/some/action/1',
key2: 'http://yoursite.com/some/action/2',
/* ... */
};
$('input:radio').click(function() {
var $rb = $(this);
for (var key in actionMap) {
if ($rb.hasClass(key))
$rb.closest('form').attr('action', actionMap[key]);
}
});
});
or something. You could also use an HTML5-style "data-" attribute to store the URLs directly on the radio button elements, or a key fragment of the URL. (Also might want to handle the "change" event the same way, etc.)
The one form, alternate action pages seems to be the way to go. If you're going to use classes for the radio buttons then something like this would work.
Live example
JavaScript
// override the action page based on which radio button is checked
$('#someForm').submit( function(e) {
if($('.useDefault:checked').length == 1) this.action = 'http://www.google.com';
else this.action = 'http://wikipedia.org';
});
HTML
<form id="someForm" action="#">
<input name="rad" type="radio" value="default0" class="useDefault" /><label>default0</label>
<br />
<input name="rad" type="radio" value="default1" class="useDefault" /><label>default1</label>
<br />
<input name="rad" type="radio" value="alternate0" class="useAlternate" /><label>useAlternate0</label>
<br />
<input name="rad" type="radio" value="alternate1" class="useAlternate" /><label>useAlternate1</label>
<br />
<input type="submit" value="submit"/>
</form>
I have implemented the right solution with some help from Pointy. Here is my code:
$(function() {
$('input:radio').click(function() {
var $rb = $(this);
if ($rb.hasClass('class1')){
$("#myForm").attr("action", "link1.php");
}else if($rb.hasClass('class2')){
$rb.closest('form').attr("action", "link2.php");
}
});
$('#btnProceed').click(function(){
$('#myForm').submit();
});
});

How do you change an HTML radiobutton selection from Javascript?

I need to select an HTML radiobutton (deselecting any previously selected radiobutton) on my form, from within Javascript.
How is this accomplished?
If you set the "checked" property to true on one radio button, the other button with the same name is automatically unchecked.
Thus,
document.getElementById('buttonX').checked = true;
will cause "buttonY" to be unchecked if the HTML looks like:
<input type='radio' id='buttonX' name='fred' value='X'>
<input type='radio' id='buttonY' name='fred' value='Y' checked>
edit Remember that "radio buttons" have that name because on old radios (not necessarily older than me) the station preset buttons were mechanically inter-linked such that exactly one button was pressed at all times. Fiddling with the buttons to get them all to be un-pressed was a fun but risky pastime, as most adults didn't appreciate the aesthetic appeal of a row of un-pressed radio buttons all neatly aligned.

Categories