Radio Button check in vanilla javascript is not working - javascript

My radio button checking is not working. Can anyone please help me with this? I
want to check if the radio button is checked or not. if not checked then I want this program to give an alert. But in this program whenever the radio button is not checked I am not getting the alert.
<div>
<label for="gender">Gender: </label>
<input type="radio" name="myRadio"> Male
<input type="radio" name="myRadio"> Female
<input type="radio" name="myRadio"> Other
</div>
The radio button checking function is given below:
function radioCheck(){
var radio = document.forms["myForm"]["myRadio"].value;
for (var i=0; i<radio.length; i++) {
if (radio[i].checked){
break;
}else
{
alert("No radio button is checked");
}
}
}

Okay so this is working code:
function radioCheck(){
const radioList = document.getElementsByName("myRadio")
let notChecked = false;
for(let i = 0; i < radioList.length; i ++){
if(radioList[i].checked){
return;
} else {
notChecked = true;
}
}
if(notChecked){
alert("No radio button is checked")
}
}
radioCheck()
To explain:
first of all you have to get all inputs by using document.getElementsByName because the only one thing that they have the same is name property which is name="myRadio" in this example
second thing I added variable notChecked which is false on initial so when it will go through all inputs and see that one of them is not selected if will show alert
then you just do normal for loop that goes through all elements and checks if they are checked
if one of them is checked it just stops for loop and returns nothing, otherwise it sets notChecked = true
after loop I just check if notChecked value is true and if it is it shows an alert
last and important thing - you have to run this function at least once to execute it so you just add radioCheck() in the end
I also added this part in html <button onclick={radioCheck()} > run again </button>
so after clicking on button "run again" you can use it again (just for test)
here is working example:
link
hope that my answer will help you out :) if you have any questions please ask

Related

How to use javascript to get the value of checked checkbox dynamically

I'm new to JavaScript.
I have a webpage that the users can search the document ID and add it to their favourite. after submitting the search criteria, it shows a list ID and a checkbox next to it. so the user can check the checkbox or uncheck it to add and remove them from their list.
My issue is my code can't get the value of the checkbox generated. for example, there are three checkbox generated, chk1,chk2,chk3. when none of them are checked, my code is working I can get the value of the checkbox. but when one of them is checked for example, chk3 is checked, when I check chk1, it still shows the value of chk3 rather than chk1. I want to get the value of that checkbox just checked. I'm struggled to make it right.
<tr><%do until results_rs.EOF%>
<td class="tdid"><%Response.Write results_rs("id")%></td>
<td><input type="checkbox" id="myCheckbox" name ="myf[]" value="<%=results_rs("id")%>" onchange="myfc()">
<script>
function myfc(){
var selchb = getSelectedChbox(this.form);
alert(selchb)
}
function getSelectedChbox(frm) {
var selchbox = null;
var chk_arr=document.getElementsByName("myf[]")
var chklength=chk_arr.length
for (k = 0; k < chklength; k++) {
if (chk_arr[k].checked == true)
selchbox=chk_arr[k].value
}
return selchbox
**strong text**// rs.close;
// connection.close
}
</script></td>
<%results_rs.MoveNext%>
</tr>
The minimal change would be to pass this into myfc:
onchange="myfc(this)"
...and then use that in myfc:
function myfc(cb){
alert(cb.value);
}
But you might look into more modern event handling with addEventListener and such.
Note that there's no need to put an id on the checkbox, and in fact, it's invalid to have more than one checkbox with the same id, so probably best to just remove the id="myCheckbox" part entirely.
IDs in JS must be unique. Use a class class="myCheckbox"
Then you can do
window.addEventListener("load",function() {
var checks = document.querySelectorAll(".myCheckbox");
for (var i=0;i<checks.length;i++) { // all .myCheckbox
checks[i].addEventListener("click",function() {
console.log(this.checked,this.value); // this specific box
var checks = document.querySelectorAll(".myCheckbox:checked");
for (var i=0;i<checks.length;i++) { // all CHECKED .myCheckbox
console.log(checks[i].value); // only checked checkboxes are shown
}
});
}
});
In your case for example
window.addEventListener("load",function() {
var checks = document.querySelectorAll(".myCheckbox");
for (var i=0;i<checks.length;i++) { // all .myCheckbox
checks[i].addEventListener("click",function() {
if (this.checked) myfc(this.value); // this specific box
});
}
});

How can I mark checkbox checked when the user input a certain value?

So I have this problem where I want to mark the checkbox checked when the user input a certain value. For example when the user inputted "FAAS" the checkbox should be check. How to do this?
Here is my code:
HTML:
<input type="text" name="faashidden" id="faashidden">
<input id="faasfrontandback" name="faasfrontandback" type="checkbox">
<label for="faasfrontandback">FAAS Front & Back</label>
and when the user will input something in faashidden and click the button the checkbox should be checked. Here is my javascript code:
var faas = $("#faashidden").val();
if (faas.value == "FAAS") {
document.getElementById("faasfrontandback").checked = true;
}
Try this:
$("#faashidden").keypress(function(e){
var faas = $("#faashidden").val();
if (faas == "FAAS") {
$("#faasfrontandback").prop('checked', true);
}
});
It adds an event listener on the input. Every time the user hits a key while focused on the input, the function checks the content of the input and checks the box if it's "FAAS".
Edit: you may also want to check the box whether the input is "FAAS" or "faas". In that case, convert the input to lowercase and compare the result with "faas". See below:
$("#faashidden").keypress(function(e){
var faas = $("#faashidden").val().toLowerCase();
if (faas == "faas") {
$("#faasfrontandback").prop('checked', true);
}
});

Select Radio Button Using Javascript with No ID

I am trying to select a radio button on a webpage using Javascript inside an Applescript. For this particular button, there is no element ID, so I'm no really sure how to select this radio button.
There's really no other identifying elements for this form (or that I see, at least).
Note: There's several radio buttons on this page, and the only unique identifier between them is the "value."
HTML:
<input type="radio" size="4" name="Level" value="p;29">
Javascript/Applescript:
do JavaScript "document.getElementById('p;29').checked = true;" in doc
If you have no other input elements, you can safely use
document.getElementsByTagName("input")[0]
Otherwise, you can do:
for (i=0; i<document.getElementsByTagName('input').length; i++) {
var myInput = document.getElementsByTagName('input')[i];
if (myInput.type == 'radio')
{
//myInput is the radio element. Do something with it
}
}
I ended up using the value and name fields to target the element and check it. Here is the working script:
do JavaScript "var elements = document.getElementsByName('Level');
for (i=0;i<elements.length;i++) {
if(elements[i].value == 'p;29') {
elements[i].checked = true;
}
}" in doc

Radio Buttons clear check when clicked again

I have a set of three radio buttons and they have mutual exclusion in them, as I implemented group name property, but the problem is, in the initial stage, none of the radio button is selected,
But when I select any of the radio button, then I cannot deselect the same, although mutual exclusion is in progress, but I want them to deselect as well.
My code aspx is:
<td>
<asp:RadioButton ID="AChk" runat="server" CssClass="itemRightAlign" GroupName="A"/>
</td>
<td>
<asp:RadioButton ID="DChk" runat="server" CssClass="itemRightAlign" GroupName="A"/>
</td>
<td>
<asp:RadioButton ID="WChk" runat="server" CssClass="itemRightAlign" GroupName="A"/>
</td>
You have both a code problem and a misunderstanding.
The misunderstanding is about how the mutual exclusion radio buttons work (or are supposed to work) (or are expected by the users to work).
The code problem is that in a mutually exclusion radio buttons group you need to initially select one of them.
So, I believe there are two ways of solving the problem:
Keep the radio buttons groud. Add a "none" button to the set, so that it works as if none of the other three are selected. And initially select this "none" button.
change the radio buttons to check boxes, so the user might select and deselect each of them. Then implement your own exclusion logic. I don't recommend this one.
You would need to use javascript...
doing binding in jquery, it's easier, and the name= should match your rendered groupname "name=" attribute...
var lastChecked = null;
$('input[name=A]').click(function(){
if (lastChecked == this) {
this.checked = false;
lastChecked = null;
}
lastChecked = this;
});
Use this to deselect:
var radios = document.getElementsByName('A');
for(var i=0; i<radios.length; i++)
{
radios[i].checked = false;
}
You can deselect a radio button by using the attribute ondblclick.
<input type="radio" name="RadioGroup1
" value="1" ondblclick="uncheckRadio();">
Apple</label>
When you double click on the radio button, just call a javascript function to set the checked property to false.
function uncheckRadio() {
var choice = document.form1.RadioGroup1;
for (i = 0; i < choice.length; i++) {
if ( choice[i].checked = true )
choice[i].checked = false;
}
}
Here is a similar implementation using the attribute ondblclickand jQuery. Also, this will allow you to include this functionality within controls with a dynamically generated client ID.
Code behind:
foreach (ListItem li in rbl.Items)
li.Attributes.Add("ondblclick", string.Format("clearCurrentRadioButtonSelection(\"{0}\")", rbl.UniqueID));
ASPX page
function clearCurrentRadioButtonSelection(controlName) {
var id = "input[name=" + controlName + "]";
$(id).each(function () {
$(this).attr('checked', false);
});
}

Highling radio buttons with JS

Here is my radio button:
<label>
<input type="radio" id="chk1" name="chooseSupp" onclick="change(this);">
Chosen Supplier
</label>
Here is my Javascript which highlights the cell:
<script type="text/javascript">
function change(obj) {
var tr=obj.parentNode.parentNode;
tr.style.backgroundColor=(obj.checked)? 'red' : 'transparent';
}
</script>
The problem is, when I click on a radio button, it highlights okay but then when I click on a different radio button, it is also highlighted, but the highlighting on the first button does not go away.
My radio button is in a loop, not sure if that is relevant to any possible solution.
Any ideas?
function change(obj) {
var tr=obj.parentNode.parentNode.parentNode;
var tbl = tr.parentNode;
var inputs = tbl.getElementsByTagName("input");
for(var i = 0;i<inputs.length;i++)
inputs[i].parentNode.parentNode.parentNode.style.backgroundColor='transparent';
tr.style.backgroundColor=(obj.checked)? 'red' : 'transparent';
}
Make all other inputs transparent first. then apply your style to the new one.
you could alternatively check if the other inputs are checked to, like you do for the current input. That would be usefull if you work with checkboxes.

Categories