On h1, the unit should be changed to either celsius or fahrenheit depending on which radio is checked. But how do I change the unit to "celsius" when C radio or "Fahrenheit" when F radio is checked?
const d = document;
const F = d.querySelector("#fahrenheit");
const C = d.querySelector("#celsius");
const checkState = () => {
if (F.checked === true) {
x = "fahrenheit";
return x;
}
if (C.checked === true) {
x = "celsius";
return x;
}
};
const unit = checkState();
const h1 = d.querySelector("h1");
h1.innerHTML = `The current unit is: ${unit}`;
<div class="unit-convert">
<input type="radio" class="unit-input" id="celsius" name="unit" checked="checked">
<label for="celsius" class="unit-label">° C</label>
<input type="radio" class="unit-input" id="fahrenheit" name="unit">
<label for="fahrenheit" class="unit-label">° F</label>
</div>
<h1></h1>
You can make a control function like this
var fahrenheit = 0;
var celsius = 0;
document.getElementById("fahrenheit").addEventListener("click", function(){
fahrenheit = 1;
celsius = 0;
control();
return fahrenheit, celsius
})
document.getElementById("celsius").addEventListener("click", function(){
fahrenheit = 0;
celsius = 1;
control();
return fahrenheit, celsius
})
function control(){
if (fahrenheit == 1) {
document.getElementById("text").innerHTML ="fahrenheit";
}
if (celsius == 1) {
document.getElementById("text").innerHTML ="celsius";
}
}
<h1 id="text"></h1>
<input type="radio" id="fahrenheit">
<input type="radio" id="celsius">
You can use addEventListener to listen for change event which gets fired when value of <input> changes.
const d = document;
const F = d.querySelector("#fahrenheit");
const C = d.querySelector("#celsius");
const checkState = () => {
if (F.checked === true) {
x = "fahrenheit";
return x;
}
if (C.checked === true) {
x = "celsius";
return x;
}
};
function check() {
const unit = checkState();
const h1 = d.querySelector("h1");
h1.innerHTML = `The current unit is: ${unit}`;
}
check();
[F, C].forEach(e => e.addEventListener("change", check));
<div class="unit-convert">
<input type="radio" class="unit-input" id="celsius" name="unit" checked="checked">
<label for="celsius" class="unit-label">° C</label>
<input type="radio" class="unit-input" id="fahrenheit" name="unit">
<label for="fahrenheit" class="unit-label">° F</label>
</div>
<h1></h1>
input elements have a dedicated onchange attribute.
It's essentially a shorther way of adding an event listener for change events.
It will run a callback whenever the input value changes.
Since we already have the name value as the input's id, we can use that to update the h1 text accordingly.
Example:
function onChange(event) {
const selectedUnit = event.id;
updateHeaderText(selectedUnit);
}
function updateHeaderText(selectedUnit = "celsius") {
const header = document.querySelector("h1");
header.innerHTML = `The current unit is: ${selectedUnit}`;
}
updateHeaderText();
<div class="unit-convert">
<input type="radio" class="unit-input" id="celsius" onchange="onChange(this)" name="unit" checked="checked">
<label for="celsius" class="unit-label">° C</label>
<input type="radio" class="unit-input" id="fahrenheit" onchange="onChange(this)" name="unit">
<label for="fahrenheit" class="unit-label">° F</label>
</div>
<h1></h1>
Related
Hi I am trying to make a form, where are the fields are required, including one of two radio buttons, but for some reason the .checked property will not work neither if I am selecting it like this document.querySelector('input[name="radio"]:checked')... What am I not seeing?
As you can see I was trying different approaches but something is missing
let contactForm = document.querySelector('.contact-form');
let firstName = document.getElementById('first-name');
let lastName = document.getElementById('last-name');
let textarea = document.getElementById('message');
// let radioBtn = document.querySelector('input[name="radio"]:checked');
// let firstRadioBtn = document.getElementById('male').checked;
// let secondRadioBtn = document.getElementById('female').checked;
// console.log(firstRadioBtn.value, secondRadioBtn.value);
let submitBtn = document.querySelector('.btn');
let successMsg = document.querySelector('.success-message');
// let radios = document.getElementsByName('radio');
// let formValid = false;
// console.log(radios)
// for (let i = 0; i < radios.length; i++) {
// if (radios[i].checked) {
// formValid = true
// }
// }
function checkInputs() {
let firstNameInput = firstName.value;
let lastNameInput = lastName.value;
let text = textarea.value;
if (firstNameInput === '' || lastNameInput === '' || text === '') {
firstName.className = 'invalid';
lastName.className = 'invalid';
textarea.className = 'invalid';
successMsg.style.backgroundColor = '#e63946';
successMsg.style.visibility = 'visible';
successMsg.innerText = `Please fill in all the required fields`
}
if (firstNameInput !== '' && lastNameInput !== '' && text !== '') {
firstName.className = 'valid';
lastName.className = 'valid';
textarea.className = 'valid';
successMsg.style.backgroundColor = '#52b788';
successMsg.style.visibility = 'visible';
successMsg.innerText = `Thank you for your message ${firstNameInput} ${lastNameInput}`
}
console.log(`${firstName.value} ${lastName.value} \n Gender: ${radios.value} \n Message: ${message.value}`)
}
<div class="radio-btn label">
<label for="radio">Male</label>
<input type="radio" name="radio" id="male" value="male">
<label for="radio">Female</label>
<input type="radio" name="radio" id="female" value="female">
</div>
This should work!
<div class="radio-btn label">
<label for="radio">Male</label>
<input type="radio" name="radio" id="male" value="male">
<label for="radio">Female</label>
<input type="radio" name="radio" id="female" value="female">
</div>
<div id="gender-error" style="color: red; display: none">Please select the gender</div>
<button type="submit" onclick="return submit();">Submit</button>
<script>
function submit() {
var radios = document.getElementsByName("radio");
var value = ""
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
value = radios[i].value;
break;
}
}
document.getElementById("gender-error").style.display = !value ? "block" : "none";
alert(value ? "selected " + value : "no value selected");
}
</script>
Output:
hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>
var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>
You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>
I am new at this and I got stuck.
I want to sum the two results that I get with this code.
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber">
<button onclick="myFunction()">Sum</button>
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
My question is - how to sum the two results and display it in 'Total:' at the end.
And how to remove the 'Sum' button, so you can see the result from the textbox in realtime in 'Total:' ?
Thanks in advance for any help :)
Edit : I need the sum from text box and the checkbox. For example : if the user have entered '5' this number equals 5 * 97 = 485. So '5' + Name(200) should be equals to 685.
Try this. I have defined a new method to calculate total amount. Whenever the checkbox or textbox is changed, the total is updated.
$(document).ready(function() {
document.getElementById("demo").innerHTML = 0;
$('label').click(function() {
$('.option:checked').each(function() {
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
updateTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
} else {
document.getElementById("demo").innerHTML = 0;
};
updateTotal();
}
function updateTotal(){
var total = 0;
var totalAmount = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
totalAmount = total + parseInt(document.getElementById("demo").innerHTML);
$('#total').html( totalAmount +' $');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber" onkeyup="myFunction()">
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
Create a new element with ID totalHolder and inside both functions call a third function (e.g. showTotal()) to sum those values:
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
showTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
showTotal();
}
function showTotal(){
var result1= parseInt($('#total').html());
var result2= parseInt($('#demo').html());
$("#totalHolder").html(result1+result2);
}
In order to remove onClick from button, you just need to set a listener:
$(docuemnt).ready(function(){
$("#myNumber").change(function(){
//Call your function inside the listener
myFunction()
})
})
Not sure if this satisfies your issue, but you need to do a couple things.
You should wrap input fields within a form.
Why are you mixing vanilla JS and jQuery? Stick with one or the other.
You should not be afraid to modularize your application with various functions.
Move the element queries out of the processing functions, instead pass their values in.
You can toggle the class in one loop, see below.
/* jQuery plugins */
(function($) {
/** Checks-off one or more checkboxes in a list of elements. */
$.fn.check = function(checked) {
return this.each(function(index, item) {
if (checked) {
$(item).prop('checked', 'checked');
} else {
$(item).removeProp('checked');
}
});
};
})(jQuery);
$(document).ready(function() {
$('#myNumber').val(5); // Set value to 5.
$('.option').slice(0, 1).check(true); // Check the first checkbox.
$('label').on('click', handleUpdate); // Attach a 'click' listener for label
handleUpdate(); // Call the function.
});
function handleUpdate() {
var sum = sumValues();
var num = $('#myNumber').val();
var mult = getMultiplier(num);
var total = num * mult + sum;
$('#total').html(total.toFixed(2) + ' $');
$('#demo').html(mult);
}
function sumValues() {
var total = 0;
$('.option').each(function() {
var isChecked = $(this).is(':checked');
if (isChecked) total += parseInt($(this).val());
$(this).parent().toggleClass('checked', isChecked);
});
return total;
}
function getMultiplier(value) {
if (value < 5) {
return value;
}
switch (value) {
case 5:
case 6:
case 7:
return 97;
case 8:
case 9:
case 10:
return 87;
default:
return 82;
}
}
label {
display: block;
}
.checked {
background : gold !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="check-form">
<input type="number" id="myNumber">
<button onclick="handleUpdate(); return false;">Sum</button>
<p id="demo"></p>
<label><input type="checkbox" class="option" value="200" /> Name</label>
<label><input type="checkbox" class="option" value="300" /> Blah</label>
<label><input type="checkbox" class="option" value="400" /> XYZ</label>
<label><input type="checkbox" class="option" value="800" /> Something</label>
<label><input type="checkbox" class="option" value="1200" /> Item</label>
</form>
<br>Total :
<div id="total">0 $</div>
I have this simple piece of code:
var numb1 = document.getElementById("numb1")
var numb2 = document.getElementById("numb2")
var numb3 = document.getElementById("numb3")
var numb4 = document.getElementById("numb4")
var v1 = parseInt(numb1)
var v2 = parseInt(numb2)
var v3 = parseInt(numb3)
var v4 = parseInt(numb4)
var t = parseInt(0)
function myFunction() {
if (numb1.checked == true) {
var t = v1 + t
} else if (numb2.checked == true) {
var t = v2 + t
} else if (numb3.checked == true) {
var t = v3 + t
} else if (numb4.checked == true) {
var t = v4 + t
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I get that I definitely could have been more efficient when making my variables, but my problem is that even after I use parseInt() to go from string to integer, the end result in demo displays NaN. Is there something wrong with the way I defined the variables, or is it the calculation of the end value?
Because parseInt( elementObject ) doesn't return a valid number.
You wanted to parse the value, with a radix
var v1 = parseInt(numb1.value, 10);
And you have to get those values inside the function, when the value has actually changed.
Also, add some semicolons, they aren't always needed, but it's good practice to add them, and don't redeclare variables
var numb1 = document.getElementById("numb1");
var numb2 = document.getElementById("numb2");
var numb3 = document.getElementById("numb3");
var numb4 = document.getElementById("numb4");
function myFunction() {
var v1 = parseInt(numb1.value, 10);
var v2 = parseInt(numb2.value, 10);
var v3 = parseInt(numb3.value, 10);
var v4 = parseInt(numb4.value, 10);
var t = 0;
if (numb1.checked) {
t = v1 + t;
} else if (numb2.checked) {
t = v2 + t;
} else if (numb3.checked) {
t = v3 + t;
} else if (numb4.checked) {
t = v4 + t;
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I agree with the answer by adeneo. The issue is that you are parseInting an HTML Input Element.
And you already got the answer.
But I noticed that you use if..else
So, You want only one value to be selected by the user.
So, There is a short method which also help to improve the loading speed and reduce lines of codes.
using forms
function myFunction(){
t=parseInt(document.forms[0]["num"].value);
document.getElementById("demo").innerHTML=t
}
<form>
<input id="numb1" name="num" type="radio" value="10">
<input id="numb2" name="num" type="radio" value="50">
<input id="numb3" name="num" type="radio" value="80">
<input id="numb4" name="num" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
</form>
<p id="demo"></p>
How to explode value from input type checkbox for auto sum in this code ?
....................................................................................................................................................................
<form id="form1">
<input type="checkbox" value="bgh_9.99" onclick="UpdateCost()">Game 1 ( 9.99)<br>
<input type="checkbox" value="ujh_19.99" onclick="UpdateCost()">Game 2 (19.99)<br>
<input type="checkbox" value="hhb_27.50" onclick="UpdateCost()">Game 3 (27.50)<br>
<input type="checkbox" value="uu_45.65" onclick="UpdateCost()">Game 4 (45.65)<br>
<input type="checkbox" value="jjhh_87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="checkbox" value="hhh_87.20" onclick="UpdateCost()">Game 5 (87.20)<br>
<input type="text" id="totalcost" value="">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
sum += parseFloat(thisInput.value);
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
sum -= parseFloat(thisInput.value);
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "";
}
}
return null;
}());
</script>
Easy way is to split() the checkbox value.
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
number = split_array[1]; // "9.99"
sum += parseFloat(number); // 9.99