Check the value of radiobutton - javascript

I am trying to see on console that which radio button is selected.There are two radio buttons.I get this error TypeError: document.getElementById(...) is null Should I use checked feauture instead of value?
<input required="required" class="form-radio" id="edit-1" name="submitted[315]" value="1" type="radio">
<input required="required" class="form-radio" id="edit-2" name="submitted[315]" value="2" checked="checked" type="radio">
var y=document.getElementById('edit-2').value;
if(y == 2)
{
console.log("no");
} else{
console.log("yes");
}

Make sure the field wich id="edit-2" exists when your script is executed.
Otherwise, use document.ready function like :
document.addEventListener("DOMContentLoaded", function(event) {
var y=document.getElementById('edit-2').value;
if(y == 2){
console.log("no");
} else{
console.log("yes");
}
});

seems to work like this:
var y = document.getElementById('edit-2').checked;
if(y) {
console.log("no");
} else{
console.log("yes");
}
<input required="required" class="form-radio" id="edit-1" name="submitted[315]" value="1" type="radio">
<input required="required" class="form-radio" id="edit-2" name="submitted[315]" value="2" checked="checked" type="radio">

Use checked instead of value when the radio buttons are not in a form.
var checkSelection = function () {
if(document.getElementsByClassName('form-radio')[0].checked)
{
console.log("yes");
}
else {
console.log("no");
}
}
<input required="required" class="form-radio" name="submitted[315]" type="radio"> Yes
<input required="required" class="form-radio" name="submitted[315]" type="radio" checked="checked"> No
<button onClick="checkSelection()">Check Selection</button>

Related

radio buttons won't check / uncheck

I have some radio buttons in my web page.
when clicking the radio button it checks but when i click again it doesn't un-check.
i tried to add a JS function onclick
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.checked == true){
this.checked = false;
}
else {
this.checked = true;
}
}))
when I added this method it allowed my to uncheck but didn't allow me to check any of them!
what can I be missing?
these are my checkboxes:
<input type="radio" id="name" name="name"><br>
<input type="radio" id="age" name="age"><br>
<input type="radio" id="email" name="email"><br>
They all have different name attribute values - therefore they can only be checked (because they're not comparing to another sibling radio value). I think you might be looking for type="checkbox" instead:
<input type="checkbox" id="name" name="name"><br>
<input type="checkbox" id="age" name="age"><br>
<input type="checkbox" id="email" name="email"><br>
Example: Hold down Ctrl (⌘ on mac) key to uncheck.
var radios = document.getElementsByTagName('input');
for(i=0; i<radios.length; i++ ) {
radios[i].onclick = function(e) {
if(e.ctrlKey || e.metaKey) {
this.checked = false;
}
}
}
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />
Use <input type="checkbox", not <input type="radio".
Radio button is used where you have to select one of some options (which must have same name).
For example,
<input type="radio" name="gender" id="male" value="male"> <br>
<input type="radio" name="gender" id="female" value="female"> <br>
<input type="radio" name="gender" id="other" value="other">
Know more about radio button and check boxes.
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(this.value == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 1;
}
else {
this.checked = false;
document.querySelectorAll('input[type="radio"]').forEach(x=>x.value=0);
this.value = 0;
}
}))
<input type="radio" value="0" id="name" name="test"><br>
<input type="radio" value="0" id="age" name="test"><br>
<input type="radio" value="0" id="email" name="test"><br>
This code allows the user to deselect a radio button:
document.querySelectorAll('input[type="radio"]').forEach(x => x.addEventListener('click',function(){
if(! this.value0 || this.value0 == 0){
this.checked = true;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 1;
} else {
this.checked = false;
document.querySelectorAll('input[type="radio"][name="'+this.name+'"]').forEach(x=>x.value0=0);
this.value0 = 0;
}
}))
It improves the answer of Sato Takeru.

Javascript querySelector get value condition

I am trying to get value from input radio button with querySelector, but I want to write condition "if input is checked = console log is input value, but if input is not checked = console log is 0"
My code is:
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
}
}
If i call function getVal now i get value from checked input.
but i tried to write this :
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
} else
console.log(0);
}
}
but program not working console log shows nothing.
Then i tried
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
}
if (firstVal.checked === false){
console.log(0);
}
}
And still program not working. Console log shows nothing.
My HTML code is:
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="1" onchange="showPrice();">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="2" onchange="showPrice()">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="3" onchange="showPrice()">
<label for="test4">test4</label>
<input type="radio" name="price1" id="test4" value="4" onchange="showPrice()">
</div>
Edit
I use querySelectorAll and I fixed it.
If is not checked input radio, value in console is 0.
If is checked input radio, you get value from checked radio.
Here is my new code
function getVal() {
var firstVal = document.querySelectorAll("input[name='price1']");
if (firstVal[0].checked){
console.log(firstVal[0].value);
}
if (firstVal[1].checked){
console.log(firstVal[1].value);
}
if (firstVal[2].checked){
console.log(firstVal[2].value);
}
if (firstVal[3].checked){
console.log(firstVal[3].value);
}
if(firstVal[0].checked === false && firstVal[1].checked === false && firstVal[2].checked === false && firstVal[3].checked === false){
console.log(0);
}
}
<button onclick="getVal()">test</button><div class="priceInput">
<label for="test1">test1</label>
<input type="radio" name="price1" id="test1" value="1">
<label for="test2">test2</label>
<input type="radio" name="price1" id="test2" value="2">
<label for="test3">test3</label>
<input type="radio" name="price1" id="test3" value="3">
<label for="test4">test4</label>
<input type="radio" name="price1" id="test4" value="4">
But still I dont understand why I didnt get value with this code:
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal.checked){
console.log(firstVal.value);
}
if (firstVal.checked === false){
console.log(0);
}
}
Thank for help guys. Herectic Monkey solved it.
Final code:
function getVal(){
var firstVal= document.querySelector("input[name='price1']:checked");
if (firstVal) {
console.log(firstVal.value);
} else {
console.log(0);
}
}
You can achive it using jQuery very simple,
$('.test').change(function(){
var isChecked = $(this).is(':checked');
console.log(isChecked ? $(this).val() : 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="test1">test1</label>
<input type="checkbox" name="test1" class="test" value="1">
<label for="test2">test2</label>
<input type="checkbox" name="test2" class="test" value="2">
<label for="test3">test3</label>
<input type="checkbox" name="test3" class="test" value="3">
<label for="test4">test4</label>
<input type="checkbox" name="test4" class="test" value="4">

If all three radio buttons are false, don't validate

I have three different blocks of code, with radio buttons.
The only thing that changes are id and the name of them.
What I need is: if all radio buttons are checked on the value="false" (the user choose to check all the "no"), the form won't be valid.
I'm currently using jQuery validation and all I got to have is that radio buttons are all required.
I tried with this code, but it's not working.
registerForm.validate({
rules: {
'data': {
required: {
depends: function() {
return $('.yesandno').is(':checked').val() === "false";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
EDIT:
In the end, I mixed Ele's code-reply with the jQuery validation plugin that it is used on the portal I'm working on.
This is the code:
submitHandler: function(form) {
$('#btn-register').click(() => {
if ($('.yesandno:checked[value="false"]').size() === 3) {
return false;
} else {
form.submit();
}
});
}
You could use filter and check the length:
// this filter will only return radios that are checked and have a value of false
$('.yesandno').filter(function() {
return this.checked && this.value === "false";
}).length === 3;
With a jQuery selector you can accomplish that
$('.yesandno:checked[value="false"]').size() === 3
Look at this code snippet
$('button').click(() => {
if ($('.yesandno:checked[value="false"]').size() === 3) {
console.log('All radionbuttos were checked to NO');
} else {
console.log('Either at least one Radionbutto is YES or a (YES/NO) radiobutton was not still checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data2" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data2" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<div>
<input type="radio" class="yesandno" id="yes-balance" tabindex='9' name="data3" value="true" />
<label for="yes-balance" class="yes">YES</label>
<input type="radio" class="yesandno" id="no-balance" tabindex='9' name="data3" value="false" />
<label for="no-balance" class="no">NO</label>
</div>
<br>
<button>Click to see selected value!</button>
See? the condition is true when size === 3.
You can check at least one true value to pass your validation instead of checking all three radio buttons for false to fail validation. This will be helpful to scale your HTML radio options without having to change the JQuery code again and again for the length match for false options selection.
function passValidation(){
$('.yesandno').filter(function() {
return this.checked && this.value === "true";
}).length > 0;
}
Call passValidation() function during validation and if it returns true then there is at least one radio button with Yes option selected. And false from passValidation() means no Yes option is selected.

How to check for a checkbox to be checked?

I have 2 checkboxes. I need one, not both, but at least 1 to be checked. It is not a multiple selection but zero is not accepted. If one is checked, this line will work jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click'); otherwise it should alert. The following makes it alerting all the time.
UPDATE
I am not using the submit button or I would have used the validate plugin. It is a normal button to go next in the wizard <button type="button" class="btnNext">Next step</button>
HTML
<div class="form-group">
<label for="usp-category-8" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-8" value="8" data-required="true" class="usp-input usp-input-category">
Cultura
</label>
<label for="usp-category-7" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-7" value="7" data-required="true" class="usp-input usp-input-category">
Scienze
</label>
<input type="hidden" name="usp-category-required" value="1">
</div>
JS
jQuery('.btnNext').on("click", function(){
if(jQuery(".tab-pane").is("#step1")) {
var isChecked = false;
$('input[type=checkbox]').on("change", function () {
isChecked = true;
});
if ( isChecked ) {
jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click');
} else {
alert( 'Please, check at least one checkbox!' );
}
}
});
With jQuery you can use is:
$('#form').on('submit', function(e) {
e.preventDefault();
if ($('input[name="hi"]').is(':checked')) {
console.log('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="checkbox" name="hi" value="hi">Hallo<br>
<input type="checkbox" name="gb" value="gb">Tschuss<br>
<input type="submit" value="Submit">
</form>
Adapted to your code:
$('.btnNext').click(function(e) {
e.preventDefault();
if ($('#usp-category-7').is(':checked') || $('#usp-category-8').is(':checked')) {
console.log('at least one is checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="usp-category-8" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-8" value="8" data-required="true" class="usp-input usp-input-category">
Cultura
</label>
<label for="usp-category-7" class="usp-checkbox usp-cat usp-cat-0">
<input type="checkbox" name="usp-category[]" id="usp-category-7" value="7" data-required="true" class="usp-input usp-input-category">
Scienze
</label>
<input type="hidden" name="usp-category-required" value="1">
<button class="btnNext">Next</button>
</div>
Thanks to a comment, I personally resolved it like this, making them radio buttons. But I will accept the other answer as it is correct.
jQuery('.btnNext').on("click", function(){
if(jQuery(".tab-pane").is("#step1")) {
if($('input[type=radio').is(':checked')) {
jQuery('#wiz_menu.nav-tabs > .active').next('li').find('a').trigger('click');
} else {
alert( 'Please, check at least one checkbox!' );
}
}
});

Checking label text and verifying that input field tied to it has at least x amount characters

I'm super new to this language. I have the ability to check for the label sting but I want to make sure that the input field next to it has at least 6 digits (numerical if possible)
$(document).ready(function(){
$("label:contains('6 digit')") //i get lost here
});
Markup:
<form>
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>6 digit</label><input value="1" type="text" class="check">
<label>6 digit</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<input type="submit">
</form>
Tim Bolton got it almost right, though he is checking if the value is lower than 5, he is not testing the number of digits. i would do it like this:
function isValidForm(){
var labels = $('form labels');
$(labels).each(function(){
var inputText = $(this).next();
if($(inputText).val().length < 6 || isNaN($(inputText).val())) {
$(inputText).css('color', 'red'); // you can do whatever you want to show the field is not properly filled
return false;
}
})
return true;
}
then, on form submission, all you have to do is:
$('form').submit(function(){
if(!isValidForm()){
alert('please fix the errors');
return false;
}
});
You're going to want to set the for attribute on your label's. You'll also want to set an ID for the inputs for the label to recognize. That should arm you with the proper hooks to do what you want (or at least be set up appropriately).
With your current setup, try:
<script>
$(document).ready(function(){
$('#submit').click(function(event) {
event.preventDefault();
$('label').each(function() {
var len = $(this).next().length;
if(len < 5) {
alert('Too Short!');
} else { $('#form').submit();
});
})
});
</script>
<form id="form">
<label>Test</label><input value="asdfassd1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>6 digit</label><input value="1" type="text" class="check">
<label>6 digit</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<input type="submit" id="submit">
</form>
The purpose of a label is to be associated with a form-related element via an id:
<label for="digits">Enter Digits</label>
<input type="text" id="digits" />
See documentation for label. Given that all your inputs should have an id if they have a label, try the following:
$('#inputID').each(function() {
if (!$(this).val().match(/^\d{6,}$/)) {
alert('incorrect formatting!');
}
});
which tests the value of the selected input against a regular expression for "all digits, at least six".
jsFiddle demo
I think regular expressions are the most concise and portable way of validating simple inputs.
If at all possible, find an easy way to distinguish the fields you need to validate, like Tim Bolton suggested with ID attributes on the elements, or perhaps by CSS Classes like below (i.e., the "needs6" class):
<form>
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>6 digit</label><input value="1" type="text" class="check needs6">
<label>6 digit</label><input value="1" type="text" class="check needs6">
<label>Test</label><input value="1" type="text" class="check">
<input type="submit" />
</form>
Then your jQuery selector becomes much simpler (i.e., $("input.needs6")).
Once you have your inputs selected, there are many ways to validate them.
Personally, I would use the following method:
$(document).ready(function() {
var testFor6 = function () {
var allHave6 = true;
$("input.needs6").each(function () {
var input = $(this);
var value = input.val();
if (!value.match(/\d{6}/g)) {
allHave6 = false;
input.addClass('doesNotHave6');
} else {
input.removeClass('doesNotHave6');
}
});
return allHave6;
};
$('input[type="submit"]').click(function (e) {
var allHave6 = testFor6();
if (!allHave6) {
e.preventDefault(); //Cancel event-bubbling.
}
return allHave6; //Prevent form submission when false.
});
});
If you want to see this in action, pop it into http://jsfiddle.net/ and test it, although you may want to combine this with some sample CSS classes to see it working. Samples below.
.needs6 {background-color: yellow;}
.doesNotHave6 {background-color: red;}
Hope this helps,
Pete
Addendum:
Do you mean spaces...
<form>
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<label>Test</label><input value="1" type="text" class="check">
<!-- here? --><label><!-- here? -->6 digit</label><!-- here? --><input value="1" type="text" class="check needs6" value="<!-- here? -->">
<label>6 digit</label><input value="1" type="text" class="check needs6">
<label>Test</label><input value="1" type="text" class="check">
<input type="submit" />
</form>
Please clarify.
Certainly!
Simply change the input loop function to any portion of the following...
$("input.needs6").each(function () {
var input = $(this);
var value = input.val();
//You can use this to trim.
var trimmedValue = value.replace(/\s\s*$/, '').replace(/^\s\s*/, '');
//You can use this to find leading whitespace.
var hasLeadingSpaces = value.match(/^\s\s*/, '');
//You can use this to find trailing whitespace.
var hasTrailingSpaces = value.match(/\s\s*$/, '');
if (hasLeadingSpaces) {
//Do something
}
if (hasTrailingSpaces) {
//Do something
}
//Check original value
if (!value.match(/\d{6}/g)) {
allHave6 = false;
input.addClass('doesNotHave6');
} else {
input.removeClass('doesNotHave6');
}
//Check trimmed value
if (!trimmedValue.match(/\d{6}/g)) {
allHave6 = false;
input.addClass('doesNotHave6');
} else {
input.removeClass('doesNotHave6');
}
});

Categories