How can I check if a field is a radio button?
I tried if(document.FORMNAME.FIELDNAME.type =='radio') but document.FORMNAME.FIELDNAME.type is returning undefined.
The html on the page is
<input name="FIELDNAME" type="radio" value="1" >
<input name="FIELDNAME" type="radio" value="0" >
Unless I am taking the whole approach wrong. My goal is to get the value of an input field, but sometimes that field is a radio button and sometimes its a hidden or text field.
Thanks.
Your example does not work because document.FORMNAME.FIELDNAME is actually an array with 2 elements (since you have 2 inputs with that name on the form). Writing if(document.FORMNAME.FIELDNAME[0].type =='radio') would work.
EDIT: Note that if you don't know if document.FORMNAME.FIELDNAME is a radio (ie you might have a text/textarea/other) it is a good idea to test if document.FORMNAME.FIELDNAME is an array first, then if the type of it's first element is 'radio'. Something like if((document.FORMNAME.FIELDNAME.length && document.FORMNAME.FIELDNAME[0].type =='radio') || document.FORMNAME.FIELDNAME.type =='radio')
In case you don't have a form then maybe go by attribute is an option.
var elements = document.getElementsByName('nameOfMyRadiobuttons');
elements.forEach(function (item, index) {
if (item.getAttribute("type") == 'radio') {
var message = "Found radiobutton with value " + item.value;
if(item.checked) {
message += " and it is checked!"
}
alert(message);
}
});
Your code should work, but you could try the following:
document.getElementById('idofinput').type == 'radio'
Edit: Your code doesn't work for the reason mihaimm mentions above
Related
I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });
I have a form with "Does this case have IR number?"
If yes, show fields. If no, hide and show others.
I am using
validate() function.
old() to keep data after failed form submission, aka validate() error messages.
JQuery show/hide for the fields.
For the radio input, I used old() like this:
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(!old('checkIR')) checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR')) checked #endif id="noIR">
to keep the checked as it is after failed validate(), but it's buggy, When I check "Yes" and refresh, it checks "No" when it must be as "Yes".
As for the show/hide, here is what I did:
// Show/Hide fields based on radio button option
$(document).ready(function() {
$('input[name="checkIR"]').click(function() {
var inputValue = $(this).attr("value")
var targetField = $("." + inputValue);
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
});
});
With a help of css:
.box {
display: none;
}
How the code works:
If yes/haveIR radio is checked: show all fields containing class="box haveIR"
Issues trying to solve:
How to fix/improve the small bug in the input old()?
If user checked "yes", how to keep the fields of yes visibile even after failed laravel validate()?
Since the radio inputs have the same name, in both cases your session has "checkIR" and when you try to check it with old('checkIR') it will return true regardless of its value. Thats why "No" is checked.
Therefore, in order to find the old selected one, you should check by its value, not whether it exists in the session or not.
Code like this should work for you;
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(old('checkIR') == 'haveIR') checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR') == 'noIR') checked #endif id="noIR">
Or;
You can use 0 and 1 for values. Since old('checkIR') will return '0' or '1' and PHP will interpret '0' as false and '1' as true the behaviour will be like you wanted.
And for keeping the related fields visible;
You can run some script when document ready and set related fields visible by input value.
$(document).ready(function() {
var input = $('input[name="checkIR"]:checked');
if (input) { // if any checked radio when document ready
var targetField = $("." + input.val());
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
}
});
Note: didn't run the script, it may have errors but you get the point.
I have a couple of radio button below. I want to get the text from the radio button I have chosen. For example: House Espresso or Guest Espresso. I have tried to use getElementsByName and for loop to get the checked value but it seems to return nothing.
Here is my HTML code:
<div class="type">
<p>Type<p>
<input type="radio" id="houseEspresso" name="singleEspresso" checked="checked"onclick="addProduct(this)">
<label for="houseEspresso">House Espresso</label><br>
<input type="radio" id="guestEspresso" name="singleEspresso" onclick="addProduct(this)">
<label for="guestEspresso">Guest Espresso</label><br>
</div>
And here is my Javascript code:
var type = document.getElementsByName("singleEspresso")
for (var i=0; i<type.length; i++){
if(type[i].checked){
var title_type=type[i].innerText
console.log(title_type)
}
}
Can anyone give me an idea to fix it? Thank you!
The problem is that you're trying to get innerText from the <input>, which has none. You need to get the <label>'s text:
for (var i=0; i<type.length; i++){
if(type[i].checked){
var title_type=type[i].nextElementSibling.innerText
console.log(title_type)
}
}
You need to find a checked input, for that you can use :checked css selector. Then you can pick any value from input DOM element which ties it to label (in your case it's id). And basing on the id you can find corresponding label.
const selectedRadioInput = document.querySelector('[name=singleEspresso]:checked');
const inputId = selectedRadioInput.id;
const label = document.querySelector(`[for=${inputId}]`);
console.log(label.innerText);
Working demo: https://jsfiddle.net/yo18mx9k/2/
You can set a value to input radio: <input type="radio" value="1">
Then just get the buttons and see which one is checked, like this:
let house = document.getElementById('houseEspresso');
let guest = document.getElementById('guestEspresso');
if (house.checked) {
console.log(house.value);
} else if (guest.checked) {
console.log(guest.value);
}
However, I would recommend that you take a look at jQuery so you can make it easier:
$("input[name='singleEspresso']:checked").val();
The function created to send an alert based on a radio box's value returning as null is firing and sending alert while radio box has a value that should not be null. Somewhere else on the page is a function that hides the tables these radios appear on, and is what initially made this task out of my reach. If this div didn't hide, and these tables weren't generated dynamically then it could have been solved by adding a required attribute to the radio. This actually works as long as the div is showing, however breaks when hidden. I've essentially been tasked to take the long way around making this radio required.
Here is the javascript
<script type="text/javascript">
$(function validate() {
$(document).submit(function() {
<%For z = 0 to TotalUnits - 1%>
if ($("input[name='checkradio<%=z%>']:checked").length == 0)
alert("Select Yes or No for Needs Repair checkbox <%=z%>");
return false;
}
<%Next%>
$("submitbutton").click(function() {
$("#formID").submit();
document.getElementsByName("checkradio").addEventListener('click',
validate);
});
});
});
</script>
Here is the HTML
<label id="checklabel" name="checklabel">The Vehicle Requires Repair</label>"
<label id="yesradio">
<input type="radio" ((name="checkradio" & z)) value="1" id="Radio1"> Yes</label>
<label id="noradio">
<input type="radio" ((name="checkradio" & z)) value="0" id="Radio0"> No</label>
Here is the script that hides the div (I cleaned the concat. but left the meat in its own tags)
<script>
<%for z = 0 to TotalUnits - 1%>
$( document ).ready(function() {
$("div.section<%=z%>").hide();
});
<%next%>
</script>
<%response.write(TmpString)%>
Here is my submit button (stripped off the label)
<input value="Submit" type="submit" id="submitbutton" name="submitbutton"
onsubmit="validate()">
The alert should only fire when the submit button is pressed and the value of the radio is null.
Because each radio button is a control it is own right, you need to check if any of the controls that are linked together (via the name attribute) are checked.
Firstly, getElementsByName() returns an array (notice the s on Elements), so there is no .value for you to check.
(Oh, and be aware that having multiple <label id="yesno"> is invalid, as elements need to have a unique id attribute. In this case you're probably best just removing the id="yesno" completely.)
But it's a lot, lot easier to do this via jQuery...
<script type="text/javascript">
$(function() {
$(document).submit(function() {
<%For z = 0 to TotalUnits - 1%>
if ($("input[name='checkradio<%=z%>']:checked").length == 0)
alert("Select Yes or No for Needs Repair checkbox <%=z%>");
return false;
}
<%Next%>
$("submitbutton").click(function() {
$("#formDVIR").submit();
});
});
});
</script>
By using the selector of input[name='checkradio<%=z%>']:checked you're asking jQuery to find all input controls with a name of checkradio1 (or whatever z is) and only those which are checked. If the length of the resultant jQuery object is more than 1 you know at least one is selected
push me or so
const myId=document.getElementById(“myId”);
myId.addEventListener(“click”, function () { alert(“message and stuff”)});
I need to use javascript so that when the one radio button is selected nothing happens but if the other one is (for example, other address) it will then validate the following fields;
street
suberb
postcode
Whilst I post this, it's probably a similar method, but when I have a checkbox and a textbox how could I make it so that the textbox must not be left empty only if the checkbox is checked...
Thanks everyone!!!! Ask for more details if needed, I'm terrible at explaining things!
/* To check radio validation in Employee Details page */
function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
{
window.open("EditEmployee`enter code here`.html","_self");
}
return false;
}
Hope this example helps you friend.
Since they will be checking the radio button when they click on it, you can add an onClick event to one of the radio buttons and not the other.
<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>
For the checkbox, when a user checks the box you should set the focus to the text input field. That way if a user moves away from that field (onBlur) you can give them an error/alert to fill in the text.
<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>
<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
I'll assume you might be using jQuery, since you didn't say. If not, then you can still take the concepts and port them to plain old javascript or whatever you're using.
Example markup
<form id="address-form">
<input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
<input type="radio" name="validate" value="no"> Don't Validate<br>
Street <input name="street"><br>
Suberb <input name="suberb"><br>
Postcode <input name="postcode"><br>
<input type="submit">
</form>
Conditional validation
Either somewhere on your page in a <script> tag or in a javascript file you include, create a submit event that will check the value of the radio input before doing the validation.
$('#address-form').submit(function(event) {
if ($('input[name=validate]:checked').val() === 'yes') {
if (!formValid()) {
event.preventDefault(); // Don't submit the form
}
}
});
// Perform validations
function formValid() {
if ($('input[name=street]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=suberb]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=postcode]').val().length == 0) {
// tell them ...
return false;
}
return true;
}
That should do the trick!
I created a jsfiddle you can mess with further if you want - http://jsfiddle.net/nilbus/JNnuX/2/
Using a checkbox instead
It's pretty similar to use a checkbox. Instead of this
if ($('input[name=validate]:checked').val() === 'yes') {
just check to see if your checkbox is checked.
if ($('input[name=validate]').attr('checked')) {
http://jsfiddle.net/nilbus/JNnuX/3/