I making the shops for my site, and but I can't understand why this conde don't wont to work...Here's the code:
<script>
function Price() {
var Quantity = document.getElementsByClassName('BUY')[0].value;
var Total = Quantity * 20;
if (!IsNan(Total)) {
document.getElementsByClassName('Total').innerHTML = Total;
document.getElementsByClassName('Quantity').innerHTML = Quantity;
} else {
document.getElementsByClassName('Total').innerHTML = "Invalid number";
document.getElementsByClassName('Quantity').innerHTML = 0
}
}
Here is the html:
<input style="margin-top:1%;" type="text" name="BUY" class="input" maxlength="1000" autocomplete="on" placeholder="Buy " onchange="Price()" required>Price for <span class="Quantity">0</span>Views:<span class="Total">0</span> Satoshis<br>
From this code I expect a print of the calculation based on the quantity but the code don't work and I get no errors...
document.getElementsByClassName('BUY') will search for elements having class 'BUY', but ur input has class 'input'
you have worng class name in the script that's why it is not working.
corrected code:(Just copy & paste it .works changed class into ID)
Because using classname it is not fetching the correct value instead it assigns Quantity as undefined refer this answer
function price(){
var Quantity=document.getElementById('buy').value;
var Total=Quantity*20;
if(Total != 'NaN'){
document.getElementById('Total').innerHTML=Total;
document.getElementById('Quantity').innerHTML=Quantity;
}else{
document.getElementById('Total').innerHTML="Invalid number";
document.getElementById('Quantity').innerHTML=0;
}
}
<input style="margin-top:1%;" type="text" name="BY" id="buy" maxlength="1000" autocomplete="on" placeholder="Buy " onkeyup="price()" required/>Price for
<span id="Quantity">0</span>
Views:<span id="Total">0</span>
Satoshis<br>
Related
I created a discount function for my order page where I have an issue that is , on my order page by default when product quantity is 1 then discounted rate show correctly in Final textbox but when I change the Quantity, like 1 to 2,3,4,5.. then my code not works and the amount show without discount rate.
I try to fix this but I not understand where is mistake and how I fix that.
Below is my code which I am using please help and tell me how I make this correct.
Your help will be really appreciate.
Thank you!
function getTotal(row = null) {
if(row) {
var disc = $('#dis_1').val();//
var dec = (disc/100).toFixed(2); //
var total = Number($("#rate_value_"+row).val()) * Number($("#qty_"+row).val()) * dec;
//total = total.toFixed(2);
var rate = Number($("#rate_value_"+row))-total;
total = total.toFixed(2);
$("#amount_"+row).val(total);
$("#amount_value_"+row).val(total);
subAmount();
} else {
alert('no row !! please refresh the page');
}
}
//**---**/
//*---*//
// get the product information from the server
function getProductData(row_id)
{
var product_id = $("#product_"+row_id).val();
if(product_id == "") {
$("#rate_"+row_id).val("");
$("#rate_value_"+row_id).val("");
$("#qty_"+row_id).val("");
$("#amount_"+row_id).val("");
$("#amount_value_"+row_id).val("");
} else {
$.ajax({
url: base_url + 'orders/getProductValueById',
type: 'post',
data: {product_id : product_id},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#rate_"+row_id).val(response.price);
$("#rate_value_"+row_id).val(response.price);
$("#dis_"+row_id).val(response.discount);
$("#dis_value_"+row_id).val(response.discount);
$("#qty_"+row_id).val(1);
$("#qty_value_"+row_id).val(1);
//DISCOUNT
var disc = $('#dis_1').val();
var dec = (disc/100).toFixed(2);
var total = Number(response.price) * dec;
var rate = Number(response.price)-total;
total = rate.toFixed(2);
$("#amount_"+row_id).val(total);
$("#amount_value_"+row_id).val(total);
subAmount();
} // /success
}); // /ajax function to fetch the product data
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
<td>
<input type="text" name="rate[]" id="rate_1" class="form-control" autocomplete="off" placeholder="Rate">
</td>
<td>
<input type="text" placeholder="Discount" name="dis[]" id="dis_1" class="form-control" autocomplete="off">
</td>
<td>
<input type="text" placeholder="Total Price" name="amount[]" id="amount_1" class="form-control" autocomplete="off">
</td>
I am using my database to fetch the amount like product real rate, discounts.
In your line of HTML
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
you are always calling getTotal with a value of 1, I think you want to instead get the value of the text box when the getTotal function is called and use that as your row value. In jquery you can get the value of the box by
row = $("#qty").val()
I am dynamically creating the inputs in the form
I want user to enter at least 'n' elements.
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
function validateForm(){
var frm = document.forms['simples'];
a = parseInt(frm.elements['myInputs_1[]'].length)
var sum = parseInt(frm.elements['myInputs_1[]'].length)
if(parseInt(sum) < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
</script>
</head>
<body>
<form name="simples" action="part.php" align="center" onsubmit="return validateForm()" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
<input type="submit" value="show me what is next">
</form>
</body>
</html>
The method validateForm() works only if number text boxes are greater than equal to 2, for 0 and 1 it does not work.
Please not that this is minimal example, in real website, I have many such divs collecting input in multiple arrays, so I am summing them over something like:
var sum = parseInt(frm.elements['myInputs_1[]'].length) + parseInt(frm.elements['myInputs_2[]'].length) + parseInt(frm.elements['myInputs_3[]'].length)
but it may happen that few of the arrays are empty.
How do I check that collectively there are atleast n inputs?
frm.elements['myInputs_1[]'] has a different behavior for each of the cases.
for no elements entered, it will be undefined
for 1 element, it only contains that element, so it does not have a length
for two elements onwards it is an object of type RadioNodeList, which is inherited from NodeList and has a length attribute.
so the validate form method changes to:
function validateForm(){
var frm = document.forms['simples'];
ele = frm.elements['myInputs_1[]'];
if(typeof ele === 'undefined'){
alert('no element at all..');
return false;
}
else if(ele.value == ""){
if (ele.length < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
else{
alert('contains one element');
return false;
}
return true;
}
and it works!
I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?
In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.
I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT, but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE, I did not find any onchange event in list provided.
Duncan.html
<html>
<head><title>Duncan Online Donut's Service</title></head>
<script type="text/javascript">
function subTotal(){
document.write("working");
const TAXRATE = 0.095;
const DONUTRATE = 0.5;
var tax = 0;
var subTotal = 0;
var total = 0;
var cakedonut = parseInt(document.getElementById("cakedonut").value);
var glazedonut = parseInt(document.getElementById("glazedonut").value);
if(isNaN(cakedonut))
cakedonut = 0;
if(isNaN(glazedonut))
glazedounut = 0;
subTotal = (cakedonut + glazedonut)* DONUTRATE ;
tax = subTotal * TAXRATE ;
total = subTotal + tax ;
document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
<body>
<h1><b><i>Duncan Online Donut's Service</i></b></h1>
<form>
Name : <input id="name" type="text" name="name"/><br><br>
#no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
#no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
tax : <input id="tax" type="text" name="tax" /><br><br>
Total : <input id="total" type="text" name="total"/><br><br>
<input type="submit"/><br><br>
</form>
</body>
</html>
JSFiddle
The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.
The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.
JSBIN link
change your function name. don't use subTotal(); and don't use document.write("working");
function subTotalnew()
{
alert('working');
}
onchange="subTotalnew() it gonna be work after input blur.
oninput="subTotalnew() it gonna be work when input entering something.
I'm getting an undefined error and don't know why this isn't working.
It's supposed to divide the rent by the amount of roommates:
function splitRent() {
var roommates = document.getElementById("rent");
var rent = document.getElementById("rent");
var rentEach = rent / roommates;
if (document.getElementById("submit") == true) {
document.write("You each should pay" + " " + rentEach)
} else {
document.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
You want to take the value of the fields, not the fields themselves.
document.getElementById() returns the node, but you want the value of the input field:
var rent = document.getElementById("rent").value;
Also, you're getting the value of the rent twice; you want to check the roommates as well.
var roommates = document.getElementById("roommates").value;
Lastly, document.getElementById("submit") == true doesn't mean anything: you're comparing a button node with a boolean value, which doesn't make sense. If you want to check to make sure that both fields are filled, try this:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
As it stands, this allows people to enter things that are not numbers; there are two things that you could do to fix that.
Use parseInt()/parseFloat() to ensure that you're extracting a number
Check that you actually have a number before doing calculations
You'd do something like this:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
If you use the checking I've done above (rent && roommates), the validation will take place there (it checks for both empty and NaN values).
function splitRent() {
var roommates = parseInt(document.getElementById("roommates").value);
var rent = parseFloat(document.getElementById("rent").value);
var rentEach = rent / roommates;
if (roommates && rent) {
document.write("You each should pay" + " " + rentEach)
} else {
window.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
Shouldn't this be:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
Do you always get "1" for your result?