Show Popover when keydown and keyup on input - javascript

How Can I Copy Number entered by the user and show on a Popover via javascript or jquery?
I mean when user typed numbers biger than zero, forexample: 1000, popover Show 1000.
$(document).ready(function() {
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("keydown keyup", function() {
getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
if (!isNaN(price) && price > 0) {
alert(price);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
Price:<br>
<input type="number"
name="price"
id="price"
class="form-control"
min="0"
required />
</form>
</body>

You need to wait for the user to finish typing before you show the number, to do that you need to delay the alert show using a timeout function
$(document).ready(function() {
var timeout;
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("keydown keyup", function() {
clearTimeout(timeout);
timeout = getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
return setTimeout(function() {
if (!isNaN(price) && price > 0) {
$('[data-content]').attr('data-content',price);
$('[data-toggle="popover"]').popover('show');
}
}, 400);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<body>
<form>
Price:<br>
<input type="number" name="price" id="price" class="form-control" min="0" required data-toggle="popover" data-placement="bottom" data-content="0"/>
</form>
</body>

You can do it on blur event.
$(document).ready(function() {
//this calculates values automatically
getPriceAndPopUp();
$("#price").on("blur", function() {
getPriceAndPopUp();
});
});
function getPriceAndPopUp() {
var price = document.getElementById('price').value;
if (!isNaN(price) && price > 0) {
alert(price);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
Price:<br>
<input type="number" name="price" id="price" class="form-control" min="0" required />
</form>
</body>

Related

javascript event handler not working (button click - google says null)

I've looked over a number of threads here of similar problems to little avail - I can't figure out exactly what's going wrong here. Google claims that the element I'm trying to reference is null
Uncaught TypeError: Cannot read property 'addEventListener' of null at sales.js:12
and no matter how I've tried to fix it, it doesn't seem to work. As you can see in the js code, I've tried a number of ways of fixing it based on stuff I've found here.
Originally the <script src ="sales.js"> in the HTML file was up in the head, but I read in some pages here that putting it there can make it load before everything else and to put it down before the HTML closing tag.
Any suggestions?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main>
<h1>Sales Calculator</h1>
<p>Complete the form and click "Calculate".</p>
<fieldset>
<legend>
Item Information
</legend>
<label for="item">Item:</label>
<input type="text" id="item" ><br>
<label for="price">Price:</label>
<input type="text" id="price" ><br>
<label for="discount">Discount %:</label>
<input type="text" id="discount" ><br>
<label for="taxRate">Tax Rate:</label>
<input type="text" id="taxRate" ><br>
<label for="total">Discount Price:</label>
<input type="text" id="discountPrice" disabled ><br>
<label for="salesTax">Sales Tax:</label>
<input type="text" id="salesTax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br><br>
<div id="buttons">
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br></div>
</fieldset>
<pre>© Fall 2020 Rob Honomichl - Dakota State University</pre>
</main>
</body>
<script src="sales.js"></script>
</html>
JS Code:
//"use strict"
var $ = function (id) {
return document.getElementById(id);
};
//window.addEventListener("DOMContentLoaded", () => {
//$("#calculate").addEventListener("click", processEntries);
//});
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("#calculate").addEventListener("click", processEntries);
});
//window.onload = function(){
//$("#calculate").addEventListener("click", processEntries);
//};
const processEntries = () => {
//Gather User Input
//var item = document.querySelector("#item").value;
var price = parseFloat(document.querySelector("#price").value).toFixed(2);
var discount = parseInt(document.querySelector("#discount").value);
var taxRate = parseInt(document.querySelector("#taxRate").value);
//Calculate Discounted Price
function discountPriceCalc(price, discount) {
const disPrice = price * (discount/100);
return disPrice.toFixed(2);
}
//Calculate Sales Tax
function salesTaxCalc(discountPrice, taxRate) {
const taxTotal = price * (taxRate/100);
return taxTotal.toFixed(2);
}
//Calculate Total
function totalCalc(discountPrice, salesTax) {
return ((Number(discountPrice) + Number(salesTax).toFixed(2)));
}
//Calculate the disabled text box values
var discountPrice = discountPriceCalc(price, discount);
var salesTax = salesTaxCalc(discountPrice, taxRate);
var Total = totalCalc(discountPrice, salesTax);
//Update Text Boxes
document.getElementById("discountPrice").value = discountPrice;
document.getElementById("salesTax").value = salesTax;
document.getElementById("total").value = Total;
//set focus to Item box after
document.getElementById("item").focus();
};
You need to get rid of the # in the getElementById call to properly locate the element.
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("calculate").addEventListener("click", processEntries);
});

Disable button if a sum of number inputs is of certain value (JS)

Given this HTML code:
<body onload="assessSum()">
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>
</body>
What would be a function that would disable the submit button, if the sum of the 2 input fields is greater than a certain value?
My JavaScript/Jquery code doesn't seem to work:
function assessSum(){
var total = 0;
var maximum = 5;
var bt = document.getElementById('sub');
$.each($("input"),function(){
total += parseInt($(this).val()) || 0;
});
if(total > maximum){
bt.disabled = true;
}
else{
bt.disabled = false;
}
}
You need to run the function on change event of the inputs.
$(':input').on('change', assessSum);
function assessSum() {
var total = 0;
var maximum = 5;
var bt = document.getElementById('sub');
$("input").each((i, el) => {
total += (parseInt(el.value) || 0);
});
if (total > maximum) {
bt.disabled = true;
} else {
bt.disabled = false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>
The disabling can also be done like this:
$('#sub').attr('disabled', (total > maximum));

call a JS function inside an event method

I hope I'm not repeating a question but I've searched around and couldnt find help so I thought I should ask directly, I'm still a beginner and this is an assignment for my class so please be as thorough as possible
I'm trying to create a form where as the user clicks on another field, it checks if the input he put in the first one is as required by the website, without having to click enter or a submit button.
this is the HTML file.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function(){
$("div.ID").focusin(function(){
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").focusout(function(){
$(this).css("background-color", "#FFFFFF");
userid_validation(userid,5,12);
});
});
</script>
</head>
<body>
<div class="ID" >
User ID: <input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password: <input type="text" name="psw" size="12" />
</div>
</body>
</html>
and this is the JS file
function userid_validation(userid,mx,my)
{
var uid_len = userid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to "+my);
//uid.focus();
return false;
}
return true;
}
I'm most probably doing something completely wrong but I don't know what. thanks in advance !
You need to apply focusin and foucsout on input elements. Currently you have applied it on div. Also you have code error on calling following function,
userid_validation(userid, 5, 12); // userid not defined.
Please check if this works.
function userid_validation(userid, min, max) {
var uid_len = userid.length;
if (uid_len == 0 || uid_len > max || uid_len < min) {
alert("User Id should not be empty / length be between " + min+ " to " + max);
//uid.focus();
return false;
}
return true;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
$(document).ready(function() {
$("div.ID").find('input').focusin(function() {
$(this).css("background-color", "#FFFFCC");
});
$("div.ID").find('input').focusout(function() {
$(this).css("background-color", "#FFFFFF");
userid_validation($(this).val(), 5, 12);
});
});
</script>
</head>
<body>
<div class="ID">
User ID:
<input type="text" name="userid" size="12" />
</div>
<div class="pass">
Password:
<input type="text" name="psw" size="12" />
</div>
</body>
</html>

Calculate total from number input and set to number input

Helo, I have some problems on my calculate script, why I can not calculate example: 23+20*2=86 when I calculate he gather + and not * why ? hre is the script
<script type='text/javascript'>
$(window).load(function(){
$('div#cont-sum-fields').on('change', 'input', function() {
var total = 0;
$('#cont-sum-fields').find('input[id^="cont-sum"]').each(function() {
if ($(this).val() !== "") total += parseFloat($(this).val())
});
$('#cont-sum-fields').find('#total-cont-sum').val(total);
});
});//]]>
</script>
<body>
<div id='cont-sum-fields'>
<input type="number" id="cont-sum-1" />
<input type="number" id="cont-sum-2" />
<input type="number" id="cont-sum-3" />
<input id="total-cont-sum" type="number" disabled />
</div>
</body>
where I wrong?
Is this what you want?
$(window).load(function(){
$('div#cont-sum-fields').on('change', 'input', function() {
var total = (parseInt($( "#cont-sum-1" ).val()) + parseInt($( "#cont-sum-2" ).val())) * parseInt($( "#cont-sum-3" ).val()) ;
$('#cont-sum-fields').find('#total-cont-sum').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cont-sum-fields'>
(<input type="number" id="cont-sum-1" /> +
<input type="number" id="cont-sum-2" />) x
<input type="number" id="cont-sum-3" />
<input id="total-cont-sum" type="number" disabled />
</div>

Simple -+ button for javascript text input

I've got this script which I'm using with succes, but I've tried, and failed, to get it to stop making negative numbers when substracting pass 0..
<script language="javascript" type="text/javascript">
currentvalue = 1;
function setUp() {
document.getElementById("qty").value = currentvalue;
}
function addOne() {
currentvalue++;
document.getElementById("qty").value = currentvalue;
}
function subtractOne() {
currentvalue--;
document.getElementById("qty").value = currentvalue;
}
</script>
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="qyu" class="input-text qty" />
<div onload="setUp()">
<input class="qtyplus" type="button" value="" onClick="addOne()">
<input class="qtyminus" type="button" value="" onClick="subtractOne()">
</div>
Anyone got the magic part which stop's the show at 0 ?
Thanks!
Just add an if statement here is the fiddle
and here is your subtractOne function
function subtractOne() {
if(document.getElementById("qty").value !== '0') {
currentvalue--;
document.getElementById("qty").value = currentvalue;
}

Categories