basically when you enter a value out of the specified range it gets updated to the minimum/maximum allowed, but the value of the var doesn't get updated to the max/min. (you can check by entering 1 into both forms and clicking on quote)
https://jsfiddle.net/epf4uyr6/
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
}
document.getElementById('cad').onkeyup = function() {
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}
your values not updating properly because , keyup function executing first and then onchange(cadCheck) function execute.
your current logic is inside onchange function , thats why value not updating properly.
move this line in onkeyup function , and remove it from onchange.
document.getElementById('cad').onkeyup = function() {
if (this.value >= 100) this.value = 99.99;
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}
Related
I'm new to coding and I built a Javascript calculator, but I can't get the display to clear after Im done with one calculation. Instead, the result of the first calculation goes into the input for the second calculation. For eg if I do 3+5 it'll give me 8, but if I then press 4, the display says 84 which is why its a problem. I can clear the screen via the clear button but it gets tedious after every single calculation. Thank you.
//select all the buttons
const buttons = document.querySelectorAll('button');
//select the <input type="text" class+"display" disabled> element
const display = document.querySelector('.display');
//add eventListener to each button
buttons.forEach(function(button) {
button.addEventListener('click',calculate);
});
//calculate function
function calculate(event) {
//current clicked buttons value
var clickedButtonValue = event.target.value;
if(clickedButtonValue === '=') {
//check if the display is not empty then only do the calculation
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
}
//if any key except "=" pressed again clear display
button.addEventListener('click',clearDisplay);
} else if (clickedButtonValue === 'C') {
//clear everything on display
display.value = "";
} else {
//otherwise concatenate it to the display
display.value += clickedButtonValue;
}
}
function clearDisplay(clickedButtonValue) {
if(clickedButtonValue !== "=") {
display.value = "";
}
}
You can have a variable that keeps track of the calculated state. If it has been calculated, clear the display and reset the state
var calculated = false;
function calculate( event ){
var clickedButtonValue = event.target.value;
if ( calculated ) {
display.value = "";
calculated = false;
}
if(clickedButtonValue === '=') {
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
calculated = true;
}
}
// the rest of your logic here
}
I have this piece of code. If conditions are met i create a button "Show on Map". Now I need to run onclick event on created button that reddirects the user to a map on new URL. I tried with "window.location" in function go_to_map but it doesn't work. Any help?
function coordinates_Conv (d, m, s) {
return d + m / 60 + s / 3600;
}
function alarm(){
var lat_d = parseInt(document.getElementsByClassName("lat_deg")[0].value);
var lat_m = parseInt(document.getElementsByClassName("lat_min")[0].value);
var lat_s = parseInt(document.getElementsByClassName("lat_sec")[0].value);
var lon_d = parseInt(document.getElementsByClassName("lon_deg")[0].value);
var lon_m = parseInt(document.getElementsByClassName("lon_min")[0].value);
var lon_s = parseInt(document.getElementsByClassName("lon_sec")[0].value);
if ((coordinates_Conv (lat_d,lat_m,lat_s)<=90) && (coordinates_Conv (lat_d,lat_m,lat_s)>=0) && (coordinates_Conv (lon_d, lon_m, lon_s)<=180) && (coordinates_Conv (lon_d, lon_m, lon_s)>=0)){
document.getElementById("vypocet").innerHTML= String(Math.round(coordinates_Conv (lat_d,lat_m,lat_s)*1000)/1000) + "<br>" + String(Math.round(coordinates_Conv (lon_d, lon_m, lon_s)*1000)/1000);
var show_map = document.createElement("button","map");
show_map.setAttribute("id","map");
show_map.setAttribute("onclick", go_to_map);
show_map.innerHTML = "Show on map";
document.body.appendChild(show_map);
}
else {
alert("Invalid input");
}
}
function go_to_map(){
var targetMap = "https://www.mapurl.com/"
window.location=targetMap;
}
Your onclick handler never gets called in the first place.
To set it handler correctly, set the element's onclick directly:
show_map.onclick = go_to_map;
You need to replace show_map.setAttribute("onclick", go_to_map); with show_map.onclick = go_to_map;.
This is because onclick is an event and not an attribute.
I have a few functions and events in place that update invoice totals on change, paste, keyup and touchend which works great. However I have coded something that allows you to insert item data from a dropdown select and copies some things to input values however that does not update and now sure what changes I need to make for this to happen. Anyone have any ideas?
JSFiddle: http://jsfiddle.net/9m7q0mp8/ (if you click select product and add your see what I mean, it adds name and value, but I need it to update the subtotal and also the totals at bottom like it does, when you manually enter values in for an item).
JS:
$(document).on('click', ".item-select", function(e) {
e.preventDefault;
var product = $(this);
$('#insert').modal({ backdrop: 'static', keyboard: false }).one('click', '#selected', function(e) {
var itemText = $('#insert').find("option:selected").text();
var itemValue = $('#insert').find("option:selected").val();
$(product).closest('tr').find('#invoice_product').val(itemText);
$(product).closest('tr').find('#invoice_product_price').val(itemValue);
//updateTotals('#invoice_table');
//calculateTotal();
});
return false;
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function(e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table').on('change keyup paste touchend', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
$('#invoice_totals').on('change keyup paste touchend', '.calculate', function() {
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
isPercent = $('[name="invoice_product_discount[]"]', tr).val().indexOf('%') > -1,
percent = $.trim($('[name="invoice_product_discount[]"]', tr).val().replace('%', '')),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0) {
if(isPercent){
subtotal = subtotal - ((parseFloat(percent) / 100) * subtotal);
} else {
subtotal = subtotal - parseFloat(percent);
}
} else {
$('[name="invoice_product_discount[]"]', tr).val('');
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal() {
var grandTotal = 0,
disc = 0,
c_ship = parseInt($('.calculate.shipping').val()) || 0;
$('#invoice_table tbody tr').each(function() {
var c_sbt = $('.calculate-sub', this).val(),
quantity = $('[name="invoice_product_qty[]"]', this).val(),
price = $('[name="invoice_product_price[]"]', this).val() || 0,
subtotal = parseInt(quantity) * parseFloat(price);
grandTotal += parseFloat(c_sbt);
disc += subtotal - parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal),
finalTotal = parseFloat(grandTotal + c_ship),
vat = parseInt($('.invoice-vat').attr('data-vat-rate'));
$('.invoice-sub-total').text(subT.toFixed(2));
$('#invoice_subtotal').val(subT.toFixed(2));
$('.invoice-discount').text(disc.toFixed(2));
$('#invoice_discount').val(disc.toFixed(2));
if($('.invoice-vat').attr('data-enable-vat') === '1') {
if($('.invoice-vat').attr('data-vat-method') === '1') {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((finalTotal).toFixed(2));
$('#invoice_total').val((finalTotal).toFixed(2));
} else {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((finalTotal + ((vat / 100) * finalTotal)).toFixed(2));
$('#invoice_total').val((finalTotal + ((vat / 100) * finalTotal)).toFixed(2));
}
} else {
$('.invoice-total').text((finalTotal).toFixed(2));
$('#invoice_total').val((finalTotal).toFixed(2));
}
}
JSFIDDLE
The id problem is that it must be unique, this will not the solve problem but will prevent others, it an HTML rule (W3SCHOOLS Id description):
The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.
The input event should contain all the other events that you have listed alone, with some difference (input event answer):
Occurs when the text content of an element is changed through the user
interface.
This was another problem: e.preventDefault;, you missed the parenthesis:e.preventDefault();
The real problem was that updateTotals(); was sending the wrong element identifier, this is the correct one:updateTotals('.calculate');
$(document).on('click', ".item-select", function (e) {
e.preventDefault();
var product = $(this);
$('#insert').modal({backdrop: 'static',keyboard: false}).one('click', '#selected', function (e) {
var itemText = $('#insert').find("option:selected").text();
var itemValue = $('#insert').find("option:selected").val();
$(product).closest('tr').find('#invoice_product').val(itemText);
$(product).closest('tr').find('#invoice_product_price').val(itemValue);
updateTotals('.calculate');
calculateTotal();
});
return false;
});
Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}
I have a function that displays a countdown next to a text field for the number of characters in the field (think twitter)
<script language="javascript" type="text/javascript">
function countDown(control, maxLen, counter, typeName) {
var len = control.value.length;
var txt = control.value;
var span = document.getElementById(counter);
span.style.display = '';
span.innerHTML = (maxLen - len);
if (len >= (maxLen - 10)) {
span.style.color = 'red';
} else {
span.style.color = '';
}
}
</script>
And the next field down takes a comma separated value. Example:
tomato, apple, orange, pear
and I'd like to limit that list to 5 things (and 4 separating commas).
How can I make a similar function that counts down for the number of commas in the input.
I got this started, but it's not changing the value in the span.
my Javascript
<script language="javascript" type="text/javascript">
var max = 5;
function commaDown(area,ticker){
// our text in the textarea element
var txt = area.val();
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.val(txt.substring(0, lastComma));
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
</script>
and my html (I think the problem lies here)
<input id="choices" type="text" name="choices" class="text medium" onkeyup="commaDown('choices','limit');"/> <span id="limit">5</span><br/>
Any ideas?
Something like this (assuming you have a text field with id csv)
document.getElementById('csv').onkeydown = function(e){
if (!e) var e = window.event;
var list = this.value.split(',');
if (list.length == 5 && e.keyCode == '188' )
{
// what to do if more than 5 commas(,) are entered
// i put a red border and make it go after 1 second
this.style.borderColor ='red';
var _this = this;
setTimeout(function(){
_this.style.borderColor='';
_this.disabled=false;
},1000);
// return false to forbid the surplus comma to be entered in the field
return false;
}
}
example at http://www.jsfiddle.net/gaby/YEHXf/2/
Updated Answer
You seem to have mixed parts of jQuery in your code and that causes the script to fail
var max = 5;
function commaDown(_area, _ticker){
var area = document.getElementById(_area);
// our text in the textarea element
var txt = area.value;
// how many commas we have?
var commas = txt.split(",").length;
var span = document.getElementById(_ticker);
//var commas ++;
if(commas > max) {
// grab last comma position
var lastComma = txt.lastIndexOf(",");
// delete all after last comma position
area.value = txt.substring(0, lastComma);
//it was count with + 1, so let's take that down
commas--;
}
if (txt == '') {
commas = 0;
}
// show message
span.innerHTML = (max-commas);
}
live example at http://jsfiddle.net/z4KRd/
here is a solution:
test: http://jsbin.com/ulobu3
code: http://jsbin.com/ulobu3/edit
if you never used jsBin before, it is very easy, on the left side you have the javascript code (like if it was in your HTML code, and in your right side you have the html code.
and you just need to add /edit to the end of a jsbin url to edit that code, and save any new revisions to that code.
I added jQuery framework to make the example faster to code.