After research and lot of attempts of various implementations looking how to get radio button value from my application. Basically it is very simple radio button in file Index.cshtml :
<div class="col-md-2">
<div style="padding: 0 20px;">
<label for="star-filter2"> Projects vendors status:</label>
<fieldset id="star-filter2">
<input class="radioCheck2" id="rated-filter2" value="true" type="radio" name="starfilter2" />Rated<img src="~/images/check.png" alt="tick box" height="20" width="20" />
<br />
<input class="radioCheck2" id="rated-filter2" value="false" type="radio" name="starfilter2" />Not rated<img src="~/images/excl_mark.png" alt="excl mark" height="20" width="20" />
<br />
<input class="radioCheck2" id="rated-filter2" value="null" type="radio" name="starfilter2" />NULL<img src="~/images/excl_mark.png" alt="excl mark" height="20" width="20" />
</fieldset>
</div>
</div>
Here is my javascript code where I am trying to get selected radio button value:
$("#filter2").click(function () {
var showRated = $('#rated-filter2').is(':checked');
localStorage.setItem("showRated", showRated);
var location = $("#filter-button2").find("a").attr("href")....;
window.location.href = location;
});
In this code line: var showRated = $('#rated-filter2').is(':checked'); is working , but it is only to get value when it is checked. What I want , I want to get value of selected radio button, for example : true , "null" and any value which I insert into radio button.
I tried these lines, where I was getting 'undefined' or always false value.
$('#input[name=\'starfilter2\']:checked').val();
$('#rated-filter2:selected').val();
$('#input[name=starfilter2]:checked').val();
None of them it is not working.
Whoa, first of all, there is no reason to have multiple Ids of the same name in this case rated-filter2. IDs are supposed to be unique (like a driver's license ID or a social security number)
$(document).ready(function(){
$("input[type='button']").click(function() {
var radioValue = $("input[name='star-filter2']:checked").val();
if(radioValue){
alert("Selected: " + radioValue);
}
});
});
Or replace this
var radioValue = $("input[name='star-filter2']:checked").val();
with this
var radioValue = $("input[id='rated-filter2']:checked").val();
Keep in mind to have unique IDs.
Related
I am trying to check if a radio button is selected or not. If the "morn_before" radiobutton is selected, the data will be stored as "2", but if the "morn_after" radiobutton is selected instead, the data will be stored as "1".
Currently my code show below is not working. For example when i select the "morn_before" radiobutton, it doesnt print "morn_before checked true" in the console, despite me putting console.log("morn_before checked true") in that if statement.
HTML:
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="morn_before">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="morn_after">
<label for="morn_after">After Food</label><br><br>
</div>
Javascript:
function check() {
let user=firebase.
auth().currentUser;
let uid;
if(user!=null){
uid=user.uid;
}
var firebaseRef = firebase.database().ref();
if(document.getElementById("morn_before").checked){
console.log("morn_before checked true");
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("2");
}
else if(document.getElementById("morn_after").checked){
firebase.database().ref(uid).child('/radiobutton/').child('/morn_time/').set("1");
}
}
check();
You don't need any JavaScript for this. You can have a completely different display than the stored value.
<div class="radiobutton">
<input type="radio" id="morn_before" name="morn_time" value="2">
<label for="morn_before">Before Food</label><br>
<input type="radio" id="morn_after" name="morn_time" value="1">
<label for="morn_after">After Food</label><br><br>
</div>
Should produce the same result. The only improvement would be to set one of these to default true, in case the user chose neither. But that'd be up to you.
ADDITIONAL INFO: You are not supposed to read a radio button group that way.
You should go over some basics of HTML INPUT tag such as
https://www.geeksforgeeks.org/how-to-get-value-of-selected-radio-button-using-javascript/
I'm a total beginner to JS, trying to create a radio button with two options (left/right), in which one of the two options needs to be selected for the program to continue, or else it will display an error screen.
I've got code that will either prevent the participant from continuing no matter what they press (i.e. the error pops up regardless), or code that will allow the participant to continue no matter what (i.e. the program continues even if they don't select one of the options.) I feel like this could be something with my logical operators, but I'm really not sure. I've tried using a manual XOR and that doesn't seem to be the problem.
I'm using adapted code, so please let me know if there's anything else I can/should include!
<div class="radio"><label><input id="option1" name="option1" type="radio" value="Right" />Right</label></div>
<div class="radio"><label><input id="option1" name="option1" type="radio" value = "Left" />Left</label></div>
Code that causes the error no matter what:
<input onclick="function filledOut(id) { return (document.getElementById(id).value == 'Left')} if(filledOut('option1') ) { next(); }else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
Code that causes the program to continue:
<input onclick="function filledOut(id) { return ((document.getElementById(id).value == 'Left')|| (document.getElementById(id).value == 'Right'))} if(filledOut('option1') ) { next(); } else{ alert('Please provide a response.'); }" type="button" value="Continue" /> </div>
</div>
<form name="formName">
<input type="radio" name="option1" id="option1" value="Right"/>Right
<input type="radio" name="option2" id="option2" value="Left"/>Left
</form>
<input onclick="checkResponse()" type="button" value="Continue" />
checkResponse function will check if any options are selcted when user clicks on the continue button.
<script type="text/javascript">
function checkResponse(){
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
}
function isChecked(id){
return document.getElementById(id).checked; //returns true if any options are selected
}
</script>
You need to change the ID's to something different. In the case of radio buttons, the "name" is the radio button group. You don't need the ID's unless you are going individually look at each item, and if you give them ID's, they need to be distinct from every other ID, as well as the "name" attributes.
https://www.w3schools.com/tags/att_input_type_radio.asp
<input id="optionRight" name="groupName" type="radio" value="Right" />
<input id="optionLeft" name="groupName" type="radio" value="Left" />
Also, you can make one of the radio buttons as selected by default.
How to select a radio button by default?
<input id="option1" name="groupName" type="radio" value="Right" checked="checked" />
What I've understood is that you need to show an error if nothing is checked and continue if one of them is checked.
To do that, you will need to check if either of them is checked not checking it's value & give each radio button a unique id.
You can do something similar to this
function isChecked(id){//Instead of filledOut
return document.getElementById(id).checked;
//.checked returns true or false
}
if (isChecked('option1') || isChecked('option2')){
next();
}else{
alert("Your error message")
}
Another function to get the value if you need it:
function getCheckedBtnValue(){
if(isChecked('option1')) return document.getElementById('option1').value
if(isChecked('option2')) return document.getElementById('option2').value
return null
}
//You can also use this function to check if any of them is checked
const value = getCheckedBtnValue();
if(value){
next();
}else{
alert("Your error message");
}
Also, try not to write JavaScript inside of HTML elements it can be hard to read often.
Keep JavaScripting.
I have some code where I need to check radio buttons, and I know how to do it all client side. Here's the markup:
<input type="radio" id="rbInternalUser" name="radioUserType" value="Internal" onclick="setUserType()"/>
<label for="<%=rbInternalUser.ClientID%>">Internal User</label><br />
<input type="radio" id="rbExternalUser" name="radioUserType" value="External" onclick="setUserType()"/>
<label for="<%=rbExternalUser.ClientID%>">External User</label><br />
And the javascript:
<script type="text/javascript">
function setUserType() {
var userType = $("input[name=radioUserType]:checked").val();
}
</script>
But I need these controls set to runat=server because I'm doing some code behind stuff as well:
<input type="radio" id="rbInternalUser" name="radioUserType" value="Internal" onclick="setUserType()" runat="server" />
<label for="<%=rbInternalUser.ClientID%>">Internal User</label><br />
<input type="radio" id="rbExternalUser" name="radioUserType" value="External" onclick="setUserType()" runat="server" />
<label for="<%=rbExternalUser.ClientID%>">External User</label><br />
In that case, how do I find out which button is selected? It doesn't seem like the usual $("#<%=myControl.ClientID%>") will work here. I've tried a few things, and this seems close:
<script type="text/javascript">
function setUserType() {
var radioUserType = $("#<%=rbInternalUser.ClientID%>").prop("name");
var userType = $("input[name=" + radioUserType + "]:checked").val();
}
</script>
radioUserType is getting the client ID, but then the next line fails, saying, "unrecognized expression: input[name=ctl00$body$EditUser1$radioUserType]:checked".
What do I need to put in place of radioUserType to make this work? Is this possible? How can you get the name of the radio button group and then check which button from the group is selected?
While selecting elements using css attribute selector, make sure the value you are passing are enclosed in quotes. Example:
$("input[name='John Doe']")
Notice the single quotes around the name 'John Doe'.
Therefore, you need to change the existing statement
var userType = $("input[name=" + radioUserType + "]:checked").val();
to
var userType = $("input[name='" + radioUserType + "']:checked").val();
which will solve your problem.
i have two radio buttons, one is for fruits and dry fruits. For every radio button i display two text fields, i want to validate these text fields based on the radio button( means based on user which radio button we select).
I hardly working from morning, any idea.
Consider following just as example and will help you to sort out your problem
Below code will be part of your HTML
<input name="radio_" type="radio" value="fruit" id="fruitRadio" />
<input name="radio_" type="radio" value="dryfruit" id="dryfruitRadio" />
<input name="inputforfruitradio" type="text" value="fruit" id="fruitRadioInputText" />
<input name="inputfordryfruitradio" type="text" value="dryfruit" id="dryfruitRadioInputText" />
Above HTML code will need Javascript to work as required
$("#fruitInputText").hide();
$("#dryfruitInputText").hide();
$('input[name="radio_"]').on('change', function() {
var checked_radio = $(this).prop('id');
var inputText_id_to_be_shown = "#" + checked_radio + "InputText" ;
$(inputText_id_to_be_shown).show();
});
I have a form page in which the user can enter an ID, and the corresponding profile data is pulled from mysql and displayed in the form so that the user may edit it.
One element is a group of radios, so you may select a year level (ie "1", "2", "3", etc).
When a user provides an ID, an AJAX call is made to pre-populate the form with data, including selecting the appropriate radio.
problem:
The user must select a year level to submit the form. I check this with a verifyForm() method:
function verifyForm() {
if( !document.addStudentForm.elements["yearLevel"].checked ) {
alert( "You must select a year level before submitting." );
return false;
}
};
I expect this to check yearLevel and, if an option isn't selected, alert/return false.
However, when the yearLevel radio is pre-selected by the AJAX data, this is still behaving as if the user did not select a radio.
The radio is populated by js via the following code:
document.getElementById( "yearLevel_<?=$student['student']->get('yearLevel')?>" ).checked = true;
edit: Here is the relevant HTML.
<form name="addStudentForm" action="validation/updateStudentValidate.php" method="POST" onSubmit="return verifyForm()">
<input type="radio" value="1" name="yearLevel" disabled id="yearLevel_1" /> 1
<input type="radio" value="2" name="yearLevel" disabled id="yearLevel_2" /> 2
<input type="radio" value="3" name="yearLevel" disabled id="yearLevel_3" /> 3
<input type="radio" value="4" name="yearLevel" disabled id="yearLevel_4" /> 4
<input type="radio" value="5" name="yearLevel" disabled id="yearLevel_5" /> 5
<input type="radio" value="6" name="yearLevel" disabled id="yearLevel_6" /> 6
</form>
Question:
How can I have my javascript properly identify whether or not the radio has been checked, regardless of if it was selected by hand or programmatically?
Taken from this StackOverflow post and adapted for this example and for speed, you can have this in your AJAX success return:
var radios = document.getElementsByName('yearLevel'),
i = radios.length,
isChecked = false;
while(i--){
if (radios[i].checked) {
isChecked = true;
break;
}
}
Then when the function is called:
function verifyForm(){
if(!isChecked){
alert( "You must select a year level before submitting." );
return false;
}
};
This is assuming that you don't have any other items with the name yearLevel in your HTML.
This will actually return the value, I guess I'm unsure if you are wanting to see a specific item checked, or just that they have been checked at all. This function will do both.