Wrong behaviour of javascript applied to html5 numeric fields - javascript

I'm new to web development, and I got an error when trying to apply a fairly simple javascript code.
Suppose that we have two numeric html5 fields:
<label for="f1">First field</label>
<input type="number" name="f1" id="f1" min="0" step="1" value="100"/>
<label for="f2">Second field</label>
<input type="number" name="f2" id="f2" min="0" step="1" value="100"/>
Now I want to apply two simple rules for these fields.
When value of the first field changed, then this value (from first field) sets to the second field:
$("#f1").bind("change paste keyup", function() {
$("#f2").val($("#f1").val()); });
This works well.
The value of the second field can't exceed the value of the first field:
$("#f2").bind("change paste keyup", function() {
var f1_ = $("#f1").val();
var f2_ = $("#f2").val();
var f2_new = (f2_ > f1_)? f1_ : f2_;
$("#f2").val(f2_new); });
It works with some bugs - when the value of the second field is 10, 100, 1000, 10000, ..., and I try to decrease it, new value becomes equal to the value of the first field.
See example here

Even though the input type is number, the type of the value returned from .val() is a string. To fix this, just convert back to a number by using Number(f1_) and Number(f2_). Here is a fiddle. See that before the conversion, the console.log( typeof f1_ ) line logs string.
$("#f1").bind("change paste keyup", function()
{
$("#f2").val($("#f1").val());
});
$("#f2").bind("change paste keyup", function()
{
var f1_ = $("#f1").val();
var f2_ = $("#f2").val();
console.log( typeof f1_ );
var f2_new = (Number(f2_) > Number(f1_))? f1_ : f2_;
$("#f2").val(f2_new);
});

I like to put the + symbol in front of a String to convert it to a Number. See the following fix: http://jsfiddle.net/fXnFF/531/

Related

It seems onChange="myFunction()" is only calling my function once?

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

Converting form number field value structure

in a webpage, I asked users to input a field named "budget". I tried using the script below to create thousands separator for the entered number:
window.onload = function() {
document.getElementById("project-budget").onblur = function() {
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(0)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById("display").value = this.value.replace(/,/g, "")
}
}
<input id="project-budget" step="5" required type="text" pattern="[0-9]*" class="test input-item text-field is_number numberVal" name="et_budget" min="1">
it changes the value perfectly but the problem is that making the field value as text cause cms to not understand value in this field. so I need to change the value back to simple numbers in a hidden field and use that hidden field to insert value to database.
how can I change the value back?
for example user enters 1000000 and the script changes it to 1,000,000. I want to print 1000000 in a hidden field.
This might help.
function parseBudget(element) {
const value = parseFloat(element.value.replace(/,/g, ''));
console.log(value);
element.value = value.toFixed(0)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
document.querySelector("#forCms").value = value;
}
<input id="project-budget" step="5" required type="text" pattern="[0-9]*" onblur="parseBudget(this)" class="test input-item text-field is_number numberVal" name="et_budget" min="1">
<input type="number" id="forCms">

Calculate discount using jquery

I am calculating Discount using jquery. But I have a problem calculating the correct discount. My calculation gives me wrong result.
Here is my code
$(document).on("change keyup blur", "#chDiscount", function() {
var amd = $('#cBalance').val();
var disc = $('#chDiscount').val();
if (disc != '' && amd != '')
$('#cBalance').val((parseInt(amd)) - (parseInt(disc)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="cBalance" value="1575">
<br>
<input type="number" id="chDiscount">
I have a prepopulated value for cBalance input i.e.,1575. When I type discount value for example 500 in chDiscount input, it gives me 1020 and not 1075. And I want the value 1575 to be 1575 when there is no value or zero value in the chDiscount input. And the caculation keeps incrementing the cBalance value whenever I type new value in the chDiscount input, it does not increment from the default value.
My exptected output: When I type 500, I want the default value 1575 to be 1075. And if I delete the 1000 that I type, I want back the default value 1575 in cBalance. And If I type 5 in chDiscount, the default value would become 1570 and if I hit backspace to delete, it would become 1575 again.
How can I achieve this? Where did I go wrong? Please help.
$(document).on("change keyup blur", "#chDiscount", function() {
var amd = $('#cBalance').val();
var disc = $('#chDiscount').val();
if (disc != '' && amd != '') {
$('#result').val((parseInt(amd)) - (parseInt(disc)));
}else{
$('#result').val(parseInt(amd));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="cBalance" value="1575">
<br>
<input type="number" id="chDiscount">
<br>
<input type="number" id="result">
I added result field because otherwise you couldn't specify amd
As above mention code is just subtracting the main value. here is exact solution
<input type="number" id="cBalance" value="1575"> <br>
<input type="number" id="chDiscount"> <br>
<input type="number" id="result">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
$(document).on("change keyup blur", "#chDiscount", function() {
var main = $('#cBalance').val();
var disc = $('#chDiscount').val();
var dec = (disc/100).toFixed(2); //its convert 10 into 0.10
var mult = main*dec; // gives the value for subtract from main value
var discont = main-mult;
$('#result').val(discont);
});
JSFIDDLE

.onblur function return as a variable.value?

http://jsfiddle.net/beY6d/
I want to make a simple HTML+JS page that basically gives the user 4 text fields to write the name of some product and an extra field that displays the remaining credit in the 5th text field.
<input type="text" value="0" class="product" id="shirtItems"/><br>
<input type="text" value="0" class="product" id="pantsItems"/><br>
<input type="text" value="0" class="product" id="hatItems"/><br>
<input type="text" value="0" class="product" id="accesoryItems"/><br>
<input type="text" value="100" id="credit" disabled/>
var shirt= document.getElementById("shirtItems");
var pants= document.getElementById("pantsItems");
var hat= document.getElementById("hatItems");
var accesory= document.getElementById("accesoryItems");
var remainingDosh = document.getElementById("credit");
remainingDosh.value = 100;
There must be a .onblur (or .onfocus) event to make the "credit" field display 100 minus the sum of every other item.
Also, the price of the item must change depending on the color/type of item. Something like:
shirt.onblur = function(){
if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};
If you do typeof remainingDosh.value, you'll see that it logs string. This means you'll have to convert the string to a number if you don't want to risk having NaN show up on your page.
Convert it with parseInt() like so:
var remainingDosh.value = parseInt(remainingDosh,10)-25;
The second parameter, 10 is the radix, which in this case is decimal (though it defaults to decimal if left out I believe).
And the issue in question, as pointed out, is you're trying to do math on the element remainingDosh instead of using it's value.
Oh, and protip: instead of shirt.value, you can use this.value since the event comes from said element.
you're using remainingDosh instead of remainingDosh.value when you do your subtraction.

jQuery library to autopopulate multiple fields

I have multiple textboxes with set character limits that together make up a code. There is value in the boxes being separated for a variety of reasons. I want to be able to paste a complete code in the first textbox and have it automatically populate all the textboxes. Is there a way to do this in javascript or a jquery library for this case?
Currently I'm using jQuery autotab on each textbox and I'd prefer to keep that functionality.
DEMO
Use the onpaste event to capture the data from the user's clipboard. Then take that data and produce an array appropriate for your inputs. Then set those values using .val()
JS
$(function(){
// get first input element
pastable = document.getElementById('pastable');
// listen for the user to paste
pastable.onpaste = function(e){
// retrieve paste data as an array split to each 3 characters (3 dots below in regex)
var inputArray = e.clipboardData.getData('text/plain').match(/.../g);
// loop over input fields
$('input').each(function(i){
// place data from paste
$(this).val(inputArray[i]);
});
};
});​
HTML
<input type='text' id="pastable" maxlength="3"/>
<input type='text' maxlength="3" />
<input type='text' maxlength="3" />​
You can certainly do this in JS. I don't know about a library to do it for you through. Shooting from the hip here but maybe something like this:
Example HTML
<input type='text' data-auto-pop='true' data-group='1' data-char-limit='3'/>
<input type='text' data-auto-pop='true' data-group='1' data-char-limit='3'/>
<input type='text' data-auto-pop='true' data-group='1' data-char-limit='4'/>
Example JS
$("input[data-auto-pop='true']").change(function () {
var $this = $(this), val = $this.val();
if ($this.data("char-limit") > val.length) {
return;
} else {
var setVal = function() {
$this.val(val.slice(0, $this.data("char-limit"));
val = val.slice($this.data("char-limit"));
};
setVal();
while ($this.closest("input[data-group='"+$this.data("group")+"']") && val.length > 0) {
$this = $this.closest("input[data-group='"+$this.data("group")+"']");
setVal();
}
}
}
Probably has some mistakes in it but you should get the idea.

Categories