How to separate my event handling from HTML code - javascript

My code is working fine but is there a way to do this without having my event (onclick) in the HTML form. How can I use an eventlistener on this?
Here is the HTML:
<strong>Select Your fees Options</strong></label><br/>
<input type="checkbox" name="fee" id="exc" value="12000.00" onclick = "updateFee()" required><label>PTA and Excursion and Magazine Fee N12,000.00</label><br>
<input type="checkbox" name="fee" id="fol" value="3000.00" onclick = "updateFee()" ><label>Folder Fee <b>(optional)</b> N3,000.00</label><br>
<input type="checkbox" name="fee" id="ext" value="15000.00" onclick = "updateFee()" ><label>Extra Lesson <b>(optional)</b> N15,000.00</label><br>
<input type="checkbox" name="fee" id="clu" value="15000.00" onclick = "updateFee()"><label>Club <b>(optional)</b> N15,000.00</label><br>
<!--total fee is here-->
<p><b>Total Fee:
<input name="amt" id="amt" class="form-control number" type="text" /> <br>
Here is the JavaScript:
<script>
function updateFee(){
var totFee = 0;
var fee=document.getElementsByName("fee");
for (i = 0; i < fee.length; i++)
{
if (fee[i].checked == true)
{
totFee += parseInt(fee[i].value, 10);
}
}
amount = totFee ;
document.getElementById("amt").value = amount;
}
Thanks!

Use javascript/jQuery
In your case it would be
<strong>Select Your fees Options</strong></label><br/>
<input type="checkbox" name="fee" id="exc" value="12000.00" required><label>PTA and Excursion and Magazine Fee N12,000.00</label><br>
<input type="checkbox" name="fee" id="fol" value="3000.00"><label>Folder Fee <b>(optional)</b> N3,000.00</label><br>
<input type="checkbox" name="fee" id="ext" value="15000.00"><label>Extra Lesson <b>(optional)</b> N15,000.00</label><br>
<input type="checkbox" name="fee" id="clu" value="15000.00"><label>Club <b>(optional)</b> N15,000.00</label><br>
<!--total fee is here-->
<p><b>Total Fee:
<input name="amt" id="amt" class="form-control number" type="text" /> <br>
And then, your script:
With jQuery
$(document).ready(function() {
$('input[name=fee]').on('click', function() {
var fee = 0;
$('input[name=fee]:checked').each(function() {
fee+=parseFloat($(this).val());
});
$('#amt').val(fee);
});
});
Or, without jQuery (using your updateFee function:
// run this script after page finish loading
window.onload = function() {
// get all the checkboxes you want to listen to
var cbs = document.getElementsByName('fee');
// attach click event for each one
for(var i=0; i<cbs.length; i++) {
cbs[i].onclick=updateFee;
}
};

Related

How to disable remaining checkboxes after checking some of them

I want to disable the remaining uncheck box when I check some of them. That means if I check any two boxes and get its value then the other left uncheck box will become disable. I have made a function to get the result but I am getting this that if I check one box then all the boxes become disable.
<!DOCTYPE html>
<html>
<body>
<p id="demoo">How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>
<input type="button" value="Send order">
<br><br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
<script>
function myFunction2() {
var coffee = document.querySelectorAll("[name = coffee]"); // To get arrays by Attribute in query selector use [] to get arrays of the same attribute. We can also use ("input[type = checkbox]") to get arrays.
var txt = "";
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
txt = txt + coffee[i].value + ", ";
document.getElementById("order2").value = "You ordered a coffee with: " + txt.slice(0, -2);
}
if (coffee.length = 1) {
document.getElementById("demoo").innerHTML = i;
document.getElementById("order3").value = "Boxes left uncheck " + i;
coffee[i].setAttribute("style", "pointer-events: none; opacity: 0.5");
}
}
}
</script>
</body>
</html>
Replace your <input type="checkbox"> with radio buttons:
<input type="radio" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="radio" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="radio" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="radio" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<script>
// ignore the code below: just so that stackoverflow dont throw errors on this snipet
function myFunction2() {}
</script>
It's generally not a good idea to use inline event handlers. You can use a few css selectors and a loop here. See snippet (and comments)
// add a click handler to all clicks in the document
document.addEventListener(`click`, checkTheBoxes);
function checkTheBoxes(evt) {
// don't do anything if the click was not on one of the checkboxes
if (evt.target.name !== `coffee`) { return true; }
// get all checked checkboxes using the css selector
// "[name = coffee]:checked"
const coffee = document.querySelectorAll("[name = coffee]:checked");
// if 2 checkboxes are checked, disable the other two,
// using selector "[name = coffee]:not(:checked)")
if (coffee.length === 2) {
// [...[...]] 'spreads' the found elements into an Array
// which enables the use of 'forEach' on it.
[...document.querySelectorAll("[name = coffee]:not(:checked)")]
.forEach(cb => cb.disabled = true);
} else {
// enable if length !== 2
[...document.querySelectorAll("[name = coffee]:not(:checked)")]
.forEach(cb => cb.disabled = false);
}
}
<p id="demoo">How would you like your coffee?</p>
<input type="checkbox" name="coffee" value="100">With cream<br>
<input type="checkbox" name="coffee" value="150">With sugar<br>
<input type="checkbox" name="coffee" value="200">With milk<br>
<input type="checkbox" name="coffee" value="250">With tea<br>
<br>
<button >Send order</button>
<div id="result"></div>
function myFunction2() {
var coffee = document.getElementsByName('coffee');
var checked = [];
var maxChecked = 2;
// Order info
var order2 = document.getElementById("order2");
order2.value = "You ordered a coffee with: ";
// Loop all the checkboxes
for (var i = 0; i < coffee.length; i++) {
var chk = coffee[i];
if (chk.checked) {
// Add to checked
checked.push(chk);
// Add order info to the input
order2.value += chk.value;
if (checked.length < maxChecked) {
// Add a comma except for last element
order2.value += ", ";
}
}
if (checked.length == maxChecked) {
// Disable all and stop looping
coffee.forEach(e => e.disabled = true);
break;
}
}
// Unchecked boxes info
var order3 = document.getElementById("order3");
order3.value = "Boxes left uncheck " + (coffee.length - checked.length);
}
<p id="demoo">How would you like your coffee?</p>
<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" onclick="myFunction2()" value="100">With cream<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="150">With sugar<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="200">With milk<br>
<input type="checkbox" name="coffee" onclick="myFunction2()" value="250">With tea<br>
<br>
<input type="button" value="Send order">
<br><br>
<input type="text" id="order2" size="50">
<input type="text" id="order3" size="50">
<input type="submit" value="Submit">
</form>
I hope this is more or less what you were trying to implement.
This works fine, just add your desired condition in for loop.
You can give checkBoxes an id, then get those checkboxes by id and set them to false like below,
document.getElementById("myCheck0").disabled = true;
for multiple we can set id: "MyCheck0" and then run for loop like this:
function disableAllMyCheck() {
for(i = 0; document.getElementById("MyCheck" + i) !== null; i++) {
document.getElementById("MyCheck" + i).disabled = true;
}
}

how to compare the two input value(text and checkbox) and output the result

I want to compare the two items(text and checkbox) and output the result.
for example, 164cm and style S is A, 186cm and style B is XL
input number is height and radio button value are 3 styles(small,normal,big)
output is 164s 186b
I use a if and == display result are 'S, M, L, XL)
If user enter height and select a style, want to output a value that matches the size table prepared in advance.
I'm a beginner, so this is my plan.
this time, I want output text+radio button value
<script>
$(window).load(function(){
$(".height, .style, .style_2").keyup(function() {
var row = $(this).closest('tr');
var height = parseInt(row.find('.height').val(), 10);
var total = "height" + "style";
row.find('.total').val(isNaN(total) ? '' : total);
});
});
</script>
<table>
<tbody>
<tr id="person_total">
<td><input name="height" type="number" class="span1 height" maxlength="5"></td>
<td>
<input type="radio" id="stylebox" name="stylebox" class="style" value="s" onClick="document.getElementById('hidfield').value=this.value" />
<label for="kjc-small">S</label>
<input type="radio" id="stylebox" name="stylebox" class="style" value="n" onClick="document.getElementById('hidfield').value=this.value" />
<label for="kjc-normal">N</label>
<input type="radio" id="stylebox" name="stylebox" class="style" value="b" onClick="document.getElementById('hidfield').value=this.value" checked/>
<label for="kjc-big">B</label>
</td>
<td><input name="total" type="text" class="span1 total" readonly></td>
</tr>
</tbody>
</table>
Don't use onClick in html when you use other script controller.
You can insert input in label, when id and for no need
id can't duplicate (id="stylebox")
$(document).ready(function(){
/* get nodes */
var totalNode = $('.total');
var heightNode = $('.height');
var styleNode = $('input[name="stylebox"]');
/* initial state */
var currentTotal = 0;
var currentHeight = heightNode.val();
var currentStyle = styleNode.val();
calcTotal(); // calc state
// when [input] Height change
heightNode.on('input propertychange', function() {
currentHeight = this.value;
console.log('now height', currentHeight)
calcTotal();
})
// when [radio] Style change
styleNode.change(function() {
currentStyle = this.value;
console.log('now style', currentStyle)
calcTotal();
})
// calc.
function calcTotal() {
currentTotal = currentHeight + currentStyle;
totalNode.val(currentTotal);
console.log('now total:', totalNode.val())
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<tbody>
<tr id="person_total">
<td>
<label>
<b>Height:</b>
<input name="height" type="number" class="span1 height" value="0" maxlength="5">
</label>
</td>
<!-- radio START -->
<td>
<label>
<input type="radio" name="stylebox" class="style" value="s" />
S
</label>
<label>
<input type="radio" name="stylebox" class="style" value="n" />
N
</label>
<label>
<input type="radio" name="stylebox" class="style" value="b" checked/>
B
</label>
</td>
<!-- radio END -->
<td>
<label>
<b>Total:</b>
<input name="total" type="text" class="span1 total" readonly>
</label>
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can do it like this:
$('.height,.style').on('change, input',
function(){
$('.total').val($('.height').val() + $('.style:checked').val());
});
and please note that id should be unique in the document but all your radios has the same id (stylebox).
Live Demo
You can create a new input field which is set to read only and call a javascript function to set the value
which will append the input text and radio button field there
Total :
var size = document.getElementsById('stylebox');
var height = document.getElementsByName('height');
var size_value;
for(var i = 0; i

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

add additional value to the total

I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>

calculate value of Checked boxes using JS

I have the following html code:
I want to calculate the price associated with each checked box and display it in a text area after i click order (button). Pls help!
<div>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="submit" id = "submit_btn" onclick = "calculate()">
</fieldset>
</form>
</div>
This is usually not how it works on StackOverflow, you have to try fixing it yourself. However, I'm bored so here is a solution with HTML + Javascript.
It is bad practice to declare multiple ids with the same name, use classes instead. I changed your code a little bit. You said you want to display the code in another field, so using a form for this is not necessary.
var menuItems = document.getElementsByClassName('menuItem');
var orderButton = document.getElementById('order_btn');
var totalArea = document.getElementById('total');
var afn = 0;
orderButton.addEventListener('click', function(e) {
e.preventDefault();
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].checked) {
afn += +menuItems[i].value;
}
}
totalArea.innerHTML = "Total: " + afn + " AFN";
afn = 0;
});
<div>
<fieldset>
<legend>Resturant Menu:</legend>
<input type="checkbox" class="menuItem" value="300">
<label>Chicken-------------------------- 300 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="200">
<label>Chicken Baryani --------------- 200 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="250">
<label>Chicken Kabab ----------------- 250 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="100">
<label>Juice ----------------------------- 100 AFN</label>
<br>
<button id="order_btn">Order</button>
</fieldset>
<p id="total">Total: 0 AFN</p>
</div>
function calculate(){
var allMenuItem = $('#menuItem input[type=checkbox]');
var totalPrice = 0;
$.each(allMenuItem, function(key, element){
if($(this).is(":checked")){
totalPrice += parseFloat($(this).val());
}
});
alert("You order price is: "+ totalPrice + " Rs");
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<div id="menuItem">
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="button" value="Order" id = "submit_btn" onclick = "calculate()">
</div>
</fieldset>
</form>

Categories