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);
}
}