Javascript querySelector get value condition - javascript

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">

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.

Autofill a radiobutton

I am trying to auto fill a radio button type, I was training on this website and used it's code to test it on my google chrome console, but it returns undefined.
The website : https://benalexkeen.com/autofilling-forms-with-javascript/
the html: view-source:https://benalexkeen.com/autofilling-forms-with-javascript/
I'm trying to tick the thrid radio button using this code:
var radioElements = document.getElementsByName("input3");
for (var i=0; i<radioElements.length; i++) {
if (radioElements[i].getAttribute('value') == 'Radio3') {
radioElements[i].checked = true;
}
}
output:
I tried to adapt this code to tick on another website and still have this undefined output
I hope this will help. You might be mistaken with the attribute value
var radioElements = document.getElementsByName("input3");
for (var i=0; i<radioElements.length; i++) {
if (radioElements[i].getAttribute('value') == 'radio3') {
radioElements[i].checked = true;
}
}
<input type="radio" id="radio1" name="input3" value="radio1">
<label for="radio1">Redio 1</label><br>
<input type="radio" id="radio2" name="input3" value="radio2">
<label for="radio2">Redio 2</label><br>
<input type="radio" id="radio3" name="input3" value="radio3">
<label for="radio3">Radio 3</label>
Here is another approach in case you want something easier to read IMO.
// Instead of var I used let.
let radioElements = document.getElementsByName("input3");
radioElements.forEach((input) => {
if(input.value === "Radio3") input.checked = true;
})
<input type="radio" id="Radio1" name="input3" value="Radio1">
<label for="radio1">Radio 1</label><br>
<input type="radio" id="Radio2" name="input3" value="Radio2">
<label for="radio2">Radio 2</label><br>
<input type="radio" id="radio3" name="input3" value="Radio3">
<label for="radio3">Radio 3</label>
And about undefined, if the code you are writing doesn't return anything, it will do that. Although, it doesn't mean is not working.

Check the value of radiobutton

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>

How to add the checked input box in input text whether onload or onclick using jquery

Im getting the result now, but what I want is to Also get the checked input box and put into the input text not just only using on change event in jQuery but also on page loads. As you can see, one of the checkboxes below has been checked but not putting into the input text. Please see my code below:
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(",");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multiple">
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1" checked>1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
</div>
<div class="multiple">
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2" checked>2<br>
<input type="checkbox" value="3">3
</div>
You can do this easily like:
$(document).ready(function() {
$checks = $(":checkbox");
$checks.on('change', setResults);
function setResults() {
var string = $checks.filter(":checked").map(function(i, v) {
return this.value;
}).get().join(",");
$('#field_results').val(string);
}
setResults();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2" checked>2<br>
<input type="checkbox" value="3" checked>3
You should set values into input at first, try this:
$(document).ready(function() {
$checks = $(":checkbox");
$('#field_results').val(getCheckedValues());
$checks.on('change', function(){
$('#field_results').val(getCheckedValues());
});
});
function getCheckedValues(){
$checks = $(":checkbox");
var valuse = $checks.filter(":checked").map(function(i, v) {
return this.value;
}).get().join(",");
return valuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1" checked>1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3" checked>3<br>
<input type="checkbox" value="4">4<br>
<input type="checkbox" value="5" checked>5<br>
The easiest way to do it You can use .trigger() to set default value
$checks.trigger('change');

Knowing if all input boxes are empty in ES5 (what is the ES5 equivalent of this ES6?)

Trying to know if all input boxes with an ID starting with 'txtYear_' are empty. I have the following ES6 code, but I would like a ES5 equivalent:
Thanks!
let allNotEmpty = Array.from($("[id^='txtYear_']")).every(function(e) {
return e.value !== "";
})
console.log(allNotEmpty);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtYear_1" value="1">
<input id="txtYear_2" value="2">
<input id="txtYear_3" value="3">
<input id="txtYear_4" value="4">
<input id="txtYear_5" value="5">
<input id="txtYear_6" value="6">
<input id="txtYear_7" value="7">
You can use call to apply Array#every to any array-like object:
var allNotEmpty = Array.prototype.every.call($("[id^='txtYear_']"), function(e) {
return e.value !== "";
});
Side note: selectors like $("[id^='txtYear_']") are a good sign you should be using a class instead.
You could use the .each function from jQuery.
var allNotEmpty = true;
$("[id^='txtYear_']").each(function(i, el) {
allNotEmpty = allNotEmpty && el.value !== "";
});
console.log(allNotEmpty);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtYear_1" value="1">
<input id="txtYear_2" value="2">
<input id="txtYear_3" value="3">
<input id="txtYear_4" value="4">
<input id="txtYear_5" value="5">
<input id="txtYear_6" value="6">
<input id="txtYear_7" value="7">

Categories