I have a group of radio buttons and a text input field:
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
And I wanna the result of final price calculated by Price * Discount and updating the <p id="resultToast"> </p>.
So I did
const radios = document.querySelector('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
From the console, the radios.value not updated correctly after clicking the radio buttons. What I did wrong?
Just change:
const radios = document.querySelector('input[name="discount"]:checked');
To:
const radios = document.querySelectorAll('input[name="discount"]:checked');
See working snippet:
const radios = document.querySelectorAll('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
Reason for this is because you stored the initial
document.querySelector('input[name="discount"]:checked');
value as radios. Now that we look for all, it changes accordingly.
You are referring to a constant you defined at the beginning of your script. This will always give you the same radio button value (the one being checked at the beginning). Do something like
let discount=document.querySelector("input[name=discount]:checked").value
within your event handler function to get the current value of the radio button group.
You could also declutter(=shorten) your code a bit and make it reusable for multiple input sections that way, see below:
function qs(sel,el){return (el||document).querySelector(sel);}
function makeInteractive(frmsel){
const frm=qs(frmsel),
prc=qs("[name=price]",frm),
res=qs(".result",frm);
frm.onchange=calc;
frm.oninput= calc;
function calc(){
res.textContent=
(prc.value * qs("[type=radio]:checked",frm).value)
.toFixed(2);
}
}
makeInteractive("#frm1");
makeInteractive("#frm2");
<form id="frm1">
the first item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>
<form id="frm2">
the second item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>
I'm accessing the data for the CheckBoxes from the database, now I want to display the form for each and every checkbox if it's checked. How to achieve this?
My form design -
<div class="col-sm-12" id="roomtypes">
#foreach(var item in ViewBag.RoomTypes)
{
<input type="checkbox" id="chk_#item.id" name="RoomTypes" value="#item.id" /> #item.type<br />
<div class="col-sm-12" style="display:none;" id="Price_#item.id">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
}
</div>
I want to display the price input when checkbox is checked.
My back-end code -
ViewBag.RoomTypes = db.RoomTypes.ToList();
My code's generating this output -
My code's generating this output
You can easily do that with css. Add chkshowhide css class to your input and div and add css as per code. Your code will be as below.
<div class="col-sm-12" id="roomtypes">
#foreach(var item in ViewBag.RoomTypes)
{
<input type="checkbox" id="chk_#item.id" name="RoomTypes" value="#item.id" class="chkshowhide"/> #item.type<br />
<div class="col-sm-12 chkshowhide" id="Price_#item.id">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
}
</div>
css.
div.chkshowhide {
display: none;
}
input.chkshowhide:checked + br + div.chkshowhide {
display: block;
}
You can test sample here.
function saveData() {
$('input.chkshowhide:checked').each(function() {
var chkValue = $(this).val();
var divId = this.id.replace("chk", "Price");
var priceValue = $('#' + divId).find('input').val();
console.log('chkValue=' + chkValue + ", priceValue=" + priceValue);
// Write your save code here
});
}
div.chkshowhide {
display: none;
}
input.chkshowhide:checked + br + div.chkshowhide {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="checkbox" id="chk_1" name="RoomTypes" value="1" class="chkshowhide"> 1<br />
<div class="col-sm-12 chkshowhide" id="Price_1">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="checkbox" id="chk_2" name="RoomTypes" value="2" class="chkshowhide"> 2<br />
<div class="col-sm-12 chkshowhide" id="Price_2">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="checkbox" id="chk_3" name="RoomTypes" value="3" class="chkshowhide"> 3<br />
<div class="col-sm-12 chkshowhide" id="Price_3">
<input type="number" placeholder="Enter Price" id="PriceValue" />
</div>
<input type="button" value="Save" onclick="saveData();" />
I am using this codepen as a basis.
HTML
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
jQuery
$("input").on("click", function() {
$("#log").html($("input:checked").val() + "");
});
I have changed the radio buttons to checkboxes - but I would like to alter the js so that every selected item is then shown at the bottom of the list, rather than just the first.
The purpose is for a self awareness exercise - i.e. the user could select all statements which apply to them from a long list, and then they get an output that narrows it down to just the ones they've chosen. The form response doesn't need to be saved/submitted anywhere.
How can this be done?
$( "input" ).on( "click", function(e) {
if(e.currentTarget.checked){
var div = document.createElement("p");
div.id=e.target.value+"1";
div.innerHTML=e.target.value;
var tar=document.getElementById("log");
tar.appendChild(div);
} else {
var tag = document.getElementById(e.target.value+"1");
tag.parentNode.removeChild(tag);
}
});
You can try this its working.
Now when you click orange displayed and unchecked removed.
You need to make a couple of changes
If want to be able to select multiple radio buttons, then either keep their names different or use checkboxes.
Maintain an attribute wasChecked to toggle the checked property.
You need to iterate the checked boxes and then get their values.
Demo
$("input").on("click", function(e) {
var val = [];
var wasChecked = $(this).attr( "wasChecked" ) == "true";
if ( wasChecked )
{
$(this).prop( "checked", false );
}
else
{
$(this).prop( "checked", true );
}
$(this).attr( "wasChecked", $(this).prop( "checked") );
$("input:checked").each( function(){
val.push( $(this).val() );
});
$("#log").html( val.join( "," ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="radio" name="fruit1" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit2" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit3" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
a lot of jQuery function like .val() are designed to operate on a single element, i.e., $("input#first-name").val(), and so only return the value for the first element matched if there are multiple matches.
you will probably need a loop to extract a value for each element. fortunately, jQuery provides a function to do this as well.
$( "input" ).on( "click", function() {
var html = "";
$( "input:checked" ).each(function() {
// "this" in this context is the jQuery element in this position in the list
html += $(this).val() + "";
}
$( "#log" ).html(html);
});
$( ":checkbox" ).on('change',function(){
var li_id = 'li_'+$(this).attr('id');
if(this.checked){
$('#list').append("<li id="+li_id+">"+$(this).val()+"</li>")
}else{
$('#'+li_id).remove();
}
})
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<ul id='list'>
</ul>
This is just a simple example to add and remove items from the list if they're checked or not. At least it gives you an idea on how you can achieve it.
Now you have an array. So, maybe you need something like this?
$( "input" ).on( "click", function() {
var selectedItems = $( "input:checked" );
var results = "";
for(var i = 0; i < selectedItems.length; i++){
if(i > 0) results += ", ";
results += selectedItems[i].value;
}
$( "#log" ).html( results );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
function add(element)
{
var fruits=document.getElementById("log").innerHTML;
var fruit=element.value;
if(fruits=="")
{
document.getElementById("log").innerHTML = fruit.toString();
}
else
{
if(document.getElementById(element.id).checked == true)
{
fruits= fruits+' '+fruit.toString();
}
else
{
fruits = fruits.replace(element.value,'');
}
document.getElementById("log").innerHTML=fruits;
}
}
<form>
<div>
<input type="checkbox" value="orange" id="orange" onclick="add(this);">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" value="apple" id="apple" onclick="add(this);">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" value="banana" id="banana" onclick="add(this);">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
Plain JavaScript solutions:
With one loop:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked"),
res = new Array(checkboxes.length);
function checkChecked() {
[].forEach.call(checkboxes, (checkbox, i) => {
checkbox.addEventListener("change", function() {
checkbox.checked ? res[i] = checkbox.value : res[i] = "";
checked.innerHTML = res.join(",").replace(/(^[,]+)|([,]+$)/g, "").replace(/(,){2,}/g, ",");
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
With two loops:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked");
function getResult() {
var res = "";
[].forEach.call(checkboxes, checkbox => {
checkbox.checked ? res += checkbox.value + "," : false
})
res = res.replace(/(,$)/, "");
return res;
}
function checkChecked() {
[].forEach.call(checkboxes, checkbox => {
checkbox.addEventListener("change", function() {
checked.innerHTML = getResult();
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
The issue is:
I have four radio buttons and a check box.
Two radio buttons are with one name and two with another.
The last radio buttons with same name appear only when the check box is checked.
What I want is add the value of first radio button and the value of radio button that appears after the checkbox is checked.
So how do I total the two values using javascript or any other technique. I need it asap as I am working on a project. I need that to be done as in a shopping cart. It means if the user selects another radio button then the value of earlier one should be subtracted and the value of new one added.
<script>
// get list of radio buttons with name 'size'
var sz = document.forms['de'].elements['type'];
// loop through list
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var m=this.form.elements.total.value = this.value;
};
}
var sa = document.forms['de'].elements['glass'];
// loop through list
for (var i=0, len=sa.length; i<len; i++) {
sa[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var n=this.form.elements.total1.value = this.value;
};
}
$(document).ready(function () {
$('.a').hide();
$('#checkb').click(function () {
var $this = $(this);
if ($this.is(':checked')) {
$('.a').show();
} else {
$('.a').hide();
}
});
});
</script>
<form action="sum.php" method="post" name="de">
<fieldset>
<table align="center">
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<tr><td colspan="100sp"><label>Do You want a screen guard or a tempered glass?</label><input type="checkbox" name="screen" value="yes" id="checkb" />
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
</table>
<p><label>Repair: Rs. <input type="text" name="total" value="0" readonly="readonly" /></label></p>
<p><label>Glass: Rs. <input type="text" name="total1" value="0" readonly="readonly" /></label></p>
<p><label>Total: Rs. <input type="text" name="total2" value="0" readonly="readonly" /></label></p>
</fieldset>
</form>
You can do this with the Jquery event Change(). I have added ID names to the input text elements and this Jquery lines:
Check the comments for each line.
$(document).ready(function() {
//HIDE AND SHOW EXTRA OPTIONS
$('.a').hide();
$('#checkb').change(function() {
$('.a').toggle();
});
//CHECK WHEN ANY RADIO INPUT CHANGES
$('fieldset').on('change','input[type=radio]',function(){
//Get the Value and wich field text will change
var value = $(this).attr('value'),
target = $(this).attr('name');
$('#'+target).val(value);
//Show the total
var total = parseInt($('#type').val(),10) + parseInt($('#glass').val(),10);
$('#total').val(total);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<label>
<input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<br>
<label>
<input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<br>
<input type="checkbox" name="screen" value="yes" id="checkb" />
<label>Do You want a screen guard or a tempered glass?</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
<br>
<p>
<label>Repair: Rs.
<input type="text" id="type" name="total" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Glass: Rs.
<input type="text" id="glass" name="total1" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Total: Rs.
<input type="text" id="total" name="total2" value="0" readonly="readonly" />
</label>
</p>
</fieldset>
</form>
You can do it by using a facility given by jquery. Please check the below code
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<script type="text/javascript">
var total = 0;
$('.myradio').on('click',function(){
//Here you can get the checkbox value from data-value attribute
alert($(this).data('value');
//Total the Values
total = total + $(this).data('value');
});
</script>
In above code you can easily get the data from checkbox when it is clicked...
For testing I have the alert, so the problem seem to be before the alert.
it throws errors at:
var firstPrevClass= "categClass"+PrevClass;
var newCategory = document.getElementsByClassName(firstPrevClass);
Uncaught TypeError: undefined is not a function
Basically in function addCategory I want to create dynamically new divs with different class names (which is creating dynamically).
After that I want to append the new category after the last category.
In function addField I want to put a new field at the category which selected from the selection box.
In function getClass I get the selected className so I can create a new field in the selected div.
How to do it?
/*add new category to SelextBox*/
function addCategory() {
var categoryValue = document.getElementById("newCateg").value;
var y = document.getElementById('selectCategory');
var option = document.createElement("option");
var hid = document.getElementById("nextValue").value;
var newClass = "categClass" + hid;
option.setAttribute("class", newClass);
option.value = categoryValue;
option.text = categoryValue;
y.add(option);
var PrevClass = hid-1 ;/*i do this to get the first previous class*/
var firstPrevClass= "categClass"+PrevClass;
alert(newClass);
var newCategory = document.getElementsByClassName(firstPrevClass);
var div = document.createElement('div');
div.setAttribute('class',newClass );
var a = document.createElement('a');
a.setAttribute('class', 'titles');
var input_checkC = document.createElement('input');
input_checkC.setAttribute('type', 'checkbox');
input_checkC.setAttribute('class', 'check');
var textNodeCateg = document.createTextNode(categoryValue);
div.appendChild(a);
div.appendChild(input_checkC);
div.appendChild(textNodeCateg);
var last = newCategory.length;
newCategory[last].appendChild(div);
document.getElementById("nextValue").value++;
alert(newClass);
}
function getClass(sel) {
var x =sel.options[sel.selectedIndex].className;
document.getElementById("submitSelection").value=x;
}
function addField() {
var val = document.getElementById("submitSelection").value;
var existedCategory = document.getElementsByClassName(val);
var fieldValue = document.getElementById("newField").value;
var div = document.createElement('div');
var input_check = document.createElement('input');
input_check.setAttribute('type', 'checkbox');
input_check.setAttribute('class', 'check');
var input = document.createElement('input');
input.setAttribute('type', 'text');
var br = document.createElement('br');
var textnode = document.createTextNode(fieldValue);
div.appendChild(input_check);
div.appendChild(textnode);
div.appendChild(input);
div.appendChild(br);
existedCategory.appendChild(div);
}
<ul>
<li>Προσθέστε το όνομα της νέας κατηγορίας</li>
<p>Ονομα Kατηγορίας:
<label>
<input type="text" id="newCateg" />
</label>
<input type="button" id="addCateg" value="Προσθήκη" onclick=" addCategory()" />
</p>
<p> </p>
<li>Επιλέξετε κατω απο ποια κατηγορία θα ανήκει το νεο πεδίο και εισάγεται το όνομα του νέου πεδίου.</li>
<p>Κατηγορία:</p>
<input type="hidden" value="4" id="nextValue" />
<input type="hidden" value="" id="submitSelection" />
<select id="selectCategory" onchange="getClass(this)">
<option>Επιλογή ...</option>
<option class="categClass1">Εξοδα Κατοικίας</option>
<option class="categClass2">Εξοδα Εκπαίδευσης</option>
<option class="categClass3">Εξοδα Ψηχαγωγίας</option>
</select>
<p>Ονομα πεδίου:
<label>
<input type="text" id="newField" />
<input type="button" value="Προσθήκη" onclick="addField()" />
<br />
</label>
</p>
<div class="class_1">
<p class="titles">
<input type="checkbox" class="catChk1 check" onchange="checkAll(subCheck1,subChks)" />Εξοδα Kατοικιας</p>
<div class="field">
<input type="checkbox" class="subCheck1 check" />Ενοίκιο
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="subCheck1 check" />Θέρμανση
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="subCheck1 check" />Διάφορα Yλικά
<input type="text" />
</br>
</div>
<div class="class_2">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll(this)" />Εξοδα Εκπαίδευσης παιδιού</p>
<div class="field">
<input type="checkbox" class="check" />Φροντιστήρια
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />Βιβλία
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />Σχολική Υλη
<input type="text" />
</br>
</div>
<div class="class_3">
<p class="titles">
<input type="checkbox" class="check chk" onchange="checkAll(this)" />Για Ψυχαγωγία</p>
<div class="field">
<input type="checkbox" class="check" />
<label>Θέατρο</label>
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />
<label>Ψάρεμα</label>
<input type="text" />
</br>
</div>
<div class="field">
<input type="checkbox" class="check" />
<label>Γήπεδο</label>
<input type="text" />
</br>
</div>