jQuery result not displaying in field - javascript

For some reason I just can't get this result to display in the field using an id. It worked fine using a class but it just refuses to work using an id.
JSFiddle here http://jsfiddle.net/pbe4b/15/
Works fine:
<input id="button123" placeholder="number here"></input>
<span class="output123"></span>
Doesn't work:
<input id="button123" placeholder="number here"></input>
<input id="output123"></input>
Would love any help!

use
$('#output123').val()
instead of
$('#output123').html()
input is self closing tag so you should use val() to get value from this .

You have changed spans to inputs, and so .html() is no longer valid. The selector is fine. Change all instances of .html() to .val().
HTML:
<input id="button123" placeholder="number here"></input>
<input id="output123"></input>
JavaScript:
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
JSFiddle Here.

http://jsfiddle.net/pbe4b/19/
Vals instead of HTML since it is an input
$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}

$('#button123').keyup(function(){
var n = parseInt($(this).val());
if(n <= 35000) {
$('#output123').val(numberWithCommas((n/100*70).toFixed(2)));
}
else if(n <= 45000) {
$('#output123').val(numberWithCommas((n/100*75).toFixed(2)));
}
else {
$('#output123').val(numberWithCommas((n/100*80).toFixed(2)));
}
})
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}`enter code here`

Use $('#output123').val() to set the value.

It has nothing to do with a class/id, it is due to the fact you changed the element.
inputs do not have html(), you use val() to set the value.
Cleaned up code without all the copy and paste:
$('#button123').keyup(function(){
var n = parseInt($(this).val(), 10);
var calc;
if(n <= 35000) {
calc = n/100*70;
} else if(n <= 45000) {
calc = n/100*75;
} else {
calc = n/100*80;
}
var val = numberWithCommas(calc.toFixed(2));
$('#output123').val(val);
});

To set the value of a input use:
JS:
document.getElementById('output123').value = 'my value';
jQuery:
$('#output123').val('my value');
.html is used to replace the inner content of an item, in the case of input you need to change an attribute.

Related

Show an error when sum value is over 100

I'm trying to sum 100 on a variable ammount of input fields. I'm doing this using this Javascript:
$('.price').keyup(function () {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#totalPrice').val(sum);
});
And it works! but now i need to do two things; if the user inputs a value different than a number, or if the total value is over 100, show a hidden div.
I'm really new Javascript, and i made this code but showing an error are major words for me now.
Thank you guys!
you might want something like this:
$('.price').keyup(function() {
var sum = 0;
$('.price').each(function() {
var inputVal = +$(this).val(); //each field's value converted to number using "+"
if (!isNaN(inputVal)) {
sum += inputVal;
$('.not-num-err').hide();
} else {
$('.not-num-err').show();
return false; //stop iteration
}
});
if (sum > 100) {
$('.over-hundred-err').show();
} else {
$('.over-hundred-err').hide();
}
$('#totalPrice').val(sum);
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="price">
<input type="text" class="price">
<input type="text" class="price">
<div class="not-num-err hidden">You entered wrong number</div>
<div class="over-hundred-err hidden">Total is over 100!</div>
<p>
<label for="totalPrice">Total Price</label>
<input type="text" id="totalPrice">
check this link for more info on the unary plus (+) operator.
You can use this keyword inside it:
$('.price').keyup(function() {
if (isNaN(this.value) || (!isNaN(this.value) && this.value > 100)) {
// Do something.
alert("No!");
// Do not allow the function to proceed.
return false;
}
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#totalPrice').val(sum);
});
Working Fiddle: https://jsfiddle.net/ash06229/ydbjsx1z/
Try this:
$('.price').keyup(function () {
var sum = 0;
$('.price').each(function() {
if(sum <= 100)
{
$('.error').html("");
sum += Number($(this).val());
}
else {
$('.error').html("Sum is greater than 100").css("color","red");
}
});
$('#totalPrice').val(sum);
});

Javascript incrementing by more than one

var x1 = document.getElementById("x1");
var x2 = document.getElementById("x2");
function ThisEvent(){// needs a lot of work done to it
if (x1.value==1) {
x2.value--;
} else if (x1.value==2) {
x2.value++;
} else if (x1.value==3) {
x2.value+=5;
}
}
<input type="text" value="0" id="x1" onblur="ThisEvent()"> x1 </br>
<input type="text" value="0" id="x2"> x2
what is happening now is the digit is being added instead of incrementing when 3 is the input if x1. how do you make it increment by more than just one, without it being added it as a digit?
if (x1.value == 3) {
x2.value = parseInt(x2.value) + 5;
}
It's interpreting it as a string. You can parseInt the x2.value in the calculation.
The value of the input is a String, you need to convert it to a Number in order to perfom an addition on it.
You could do it like this:
function ThisEvent() { // needs a lot of work done to it
var valX1 = Number(x1.value);
var valX2 = Number(x2.value);
if (valX1 == 1) {
valX2--;
} else {
if (valX1 == 2) {
valX2++;
} else {
if (valX1 == 3) {
valX2 += 5;
}
}
}
x2.value = valX2;
}
jsFiddle: https://jsfiddle.net/v1utqv7f/

HTML Input type number Thousand separator

I want to have a thousand separator (e.g. 1,000,000) in my Input field. However, it has to be of type number because I need to be able to adjust its value using "step". Code:
<input type="number" id='myNumber' value="40,000" step='100'>
I tried using Javascript to adjust the value but didn't work. Any help would be appreciated. Thanks!
Using autoNumeric plugin you can made a field as numeric input with different separators.
Include plugin:
<script src="~/Scripts/autoNumeric/autoNumeric.min.js" type="text/javascript"></script>
Html:
<input type="text" id="DEMO" data-a-sign="" data-a-dec="," data-a-sep="." class="form-control">
Script:
<script>
jQuery(function($) {
$('#DEMO').autoNumeric('init');
});
</script>
You can type only number, if you input 100000,99 you will see 100.000,99.
More: https://github.com/autoNumeric/autoNumeric
Check this webdesign.tutsplus.com tutorial
Final result is summarized here (look at direct Codepen playground)
$("#formInput".on("keyup", function(event ) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
return;
}
var $this = $(this);
// Get the value.
var input = $this.val();
input = input.replace(/[\D\s\._\-]+/g, "");
input = input?parseInt(input, 10):0;
$this.val(function () {
return (input === 0)?"":input.toLocaleString("en-US");
});
});
Notes:
toLocaleString() javascript function Actually show thousands separator (example and doc)
run below code in your console to get the idea
(30000000).toLocaleString('en-US',{useGrouping:true})
You can fake this functionality by using a pseudo-element to display the comma version.
div[comma-value]{
position:relative;
}
div[comma-value]:before{
content: attr(comma-value);
position:absolute;
left:0;
}
div[comma-value] input{
color:#fff;
}
A wrapping div is required because inputs can't have pseudo elements.
<div>
<input type="number" id='myNumber' value="40000" step='100'>
</div>
And a little bit of JavaScript to insert commas every third character
myNumber.value = commify(myNumber.value)
myNumber.addEventListener("change", function(){
commify(event.target.value)
})
function commify(value){
var chars = value.split("").reverse()
var withCommas = []
for(var i = 1; i <= chars.length; i++ ){
withCommas.push(chars[i-1])
if(i%3==0 && i != chars.length ){
withCommas.push(",")
}
}
var val = withCommas.reverse().join("")
myNumber.parentNode.setAttribute("comma-value",val)
}
Check out the fiddle
Create a mask input displaying the formatted number. This solution avoids changing the type or the value of the input.
$("input.mask").each((i,ele)=>{
let clone=$(ele).clone(false)
clone.attr("type","text")
let ele1=$(ele)
clone.val(Number(ele1.val()).toLocaleString("en"))
$(ele).after(clone)
$(ele).hide()
clone.mouseenter(()=>{
ele1.show()
clone.hide()
})
setInterval(()=>{
let newv=Number(ele1.val()).toLocaleString("en")
if(clone.val()!=newv){
clone.val(newv)
}
},10)
$(ele).mouseleave(()=>{
$(clone).show()
$(ele1).hide()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="mask" type="number" value="12345.678"/>
csq recommends using the jQuery autoNumeric plugin. I found it to be very easy and intuitive to use.
My only gripe is that it forces <input type="text"> rather than <input type="number">. This means you lose the funcionality of step, but you gain users of your site being able to use commas in fields.
I guess you could use expected values of less than 1,000 as <input type="number"> and values more than 1,000 as <input type="text">
I've managed to pull it off after modifying https://stackoverflow.com/a/70726755/4829915 because:
The code didn't actually add commas due to not using Number().
It deleted the entire field when the initial value was blank.
No demo was provided.
Not saying the original approach was wrong or not, but I chose to use onfocus and onblur directly on the input itself.
Therefore, here's a revised answer:
Start with <input type="text">. You can still add min, max and step properties.
Add onfocus and onblur handlers to the <input> node:
function use_number(node) {
var empty_val = false;
const value = node.value;
if (node.value == '')
empty_val = true;
node.type = 'number';
if (!empty_val)
node.value = Number(value.replace(/,/g, '')); // or equivalent per locale
}
function use_text(node) {
var empty_val = false;
const value = Number(node.value);
if (node.value == '')
empty_val = true;
node.type = 'text';
if (!empty_val)
node.value = value.toLocaleString('en'); // or other formatting
}
<input type="text" min=0 onfocus="use_number(this)" onblur="use_text(this)">
function addCommas(nStr) { ....
In addition of yovanny's answer I create a Vue component which use this function.
Vue.component("in-n", {
template:
`<input #keyup="keyup" #keypress="isNumber($event)" v-model="text" type="text" />`,
props: ["value"],
data() {
return {
text: ""
}
},
methods: {
addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
isNumber: function (evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
evt.preventDefault();;
} else {
return true;
}
},
keyup() {
this.text = this.addCommas(this.text.replace(/,/g, ''));
this.$emit("input", parseInt(this.text.replace(/,/g, '')))
}
}
})
I found a much simpler answer:
Start with <input type="text">. You can still add min, max and step properties.
Add onfocus and onblur handlers to the <input> node:
node.addEventListener('onfocus', () => {
const value = node.value;
node.type = 'number';
node.value = Number(value.replace(/,/g, '')); // or equivalent per locale
});
node.addEventListener('onblur', () => {
const value = node.value;
node.type = 'text';
node.value = value.toLocaleString(); // or other formatting
});
When the user selects the input, it will convert to a regular numeric input with thousands separators removed, but with a normal spinner. When the user blurs the input, it reverts to formatted text.
I add an onkeyup handler that blurs the input when the "enter" key is pressed.
I have updated #CollenZhou answer https://stackoverflow.com/a/67295023/6777672 as on mouse leave, input looses focus which is annoying. I have also added all input type numbers to selector as well as class.
$('input.thousands-separator, input[type="number"]').each((i,ele)=>{
let clone=$(ele).clone(false)
clone.attr('type','text')
let ele1=$(ele)
clone.val(Number(ele1.val()).toLocaleString('en'))
$(ele).after(clone)
$(ele).hide()
clone.mouseenter(()=>{
ele1.show()
clone.hide()
})
setInterval(()=>{
let newv=Number(ele1.val()).toLocaleString('en')
if(clone.val()!=newv){
clone.val(newv)
}
},10)
$(ele).mouseleave((event)=>{
if ($(ele).is(':focus')) {
event.preventDefault();
} else {
$(clone).show()
$(ele1).hide()
}
})
$(ele).focusout(()=>{
$(clone).show()
$(ele1).hide()
})
})
try
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}

JS for each replacement of manual copy function

I am looking for way to automate this selection.
For example, I will have 10 double inputs (20 inputs total) and I don't want to write JS script for each inputs, but simply use each() function (I am open to different ways) and declare only selectors.
JsFiddle: http://jsfiddle.net/vs7fa/
Idea:
var SELECTORS_H = array();
$.each(SELECTORS_H){
$('SELECTOR_H').keyup(function () {
// do magic
$('SELECTOR_V').val(num);
});
$('SELECTOR_V').keyup(function () {
// do magic
$('SELECTOR_H').val(num);
});
}
HTML:
<label for="h_one">H_ONE:</label>
<input type="text" name="h_one">
<label for="v_one">V_ONE:</label>
<input type="text" name="v_one">
There will be more of inputs. Pattern is:
h_one, v_one
h_two, v_two
h_something, v_something
...
JS:
$(function() {
$('input[name="h_one"]').keyup(function() {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
}
else {
var num = Math.abs(one) * 1;
}
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function() {
var two = $(this).val();
if (two > 0) {
var num = Math.abs(two) * -1;
}
else {
var num = Math.abs(two) * 1;
}
$('input[name="h_one"]').val(num);
});
});
You can handle this using a selector with a common class for all your element and data-attributes to know the element and the linked elements.
HTML:
<label>H_ONE:</label>
<input type="text" class="handler" data-id="h1" data-link="v1" />
<br>
<label>V_ONE:</label>
<input type="text" class="handler" data-id="v1" data-link="h1" />
Code:
$(function () {
$('.handler').keyup(function () {
var one = $(this).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
$('input[data-id=' + $(this).attr("data-link")+']').val(num);
});
});
Demo: http://jsfiddle.net/8KgTk/
may be this...
Jsfiddle: http://jsfiddle.net/vs7fa/3/
$('input[name="h_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="v_one"]').val(num);
});
$('input[name="v_one"]').keyup(function () {
var num = DoMagic($(this));
$('input[name="h_one"]').val(num);
});
function DoMagic(element) {
var one = $(element).val();
if (one > 0) {
var num = Math.abs(one) * -1;
} else {
var num = Math.abs(one) * 1;
}
return num;
}
You should be able to perform the .each function by using jQuery and making the items the same class.
such as:
<label class="forElement" for="h_one">H_ONE:</label>
<input class="inputElement" type="text" name="h_one">
<label class="forElement"for="v_one">V_ONE:</label>
<input class="inputElement" type="text" name="v_one">
$('.forElement').each( function() {
//some code
}
You can do this without adding extra attributes if you want.
$(function () {
$('input[name^="h_"], input[name^="v_"]').keyup(function () {
var one = $(this).val();
var num = - one;
var inputType = $(this).attr("name").substr(0,1);
var inputNumber = $(this).attr("name").substr(2);
$('input[name="'+(inputType == 'v' ? 'h' : 'v')+'_' + inputNumber + '"]').val(num);
});
});
However Irvin Dominin aka Edward's solution is quite good.
Here's a sollution that doesn't require extra markup, and doesn't use string concatenation for logic. It uses $.proxy() to get correct scoping.
Fiddle

Why cant i enter decimal values in input in the following case

Before anything you need to see the effect:
jsFiddle
As you can see it is a calculator where you can put a value anywhere and covert it to other values, but the problem is that i cant enter decimal int values like 0.3 or 0.999. What is the cause of this?
var id = {
mm: 1,
cm: 10,
m: 1000,
km: 1000000
};
$('input.bx').on('keyup', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseInt(t, 10);
for (pp in id) {
if (t !== '') {
$("#" + pp).val(v / id[pp] * i);
} else {
$(".bx").val('');
}
}
});
<input type='text' class='bx' id='mm'> Milimeter<br>
<input type='text' class='bx' id='cm'> Centimeter<br>
<input type='text' class='bx' id='m'> Meter<br>
<input type='text' class='bx' id='km'> Kilometer<br>
parseInt is the "problem" since it returns integer - decimal values are not integer but floats. If you want that you must replace it with parseFloat.
1.First you need to use parseFloat because int cant have decimals.
2.Second i would use onChange.
http://jsfiddle.net/Kfkjy/10/
a working fiddle here
you have to use parseFloat and dont try to set the current focused element value cause you are over riding it while typing.
this example is working fine
http://jsfiddle.net/Mohamed_aboelenen/D6T7j/1/
$('input.bx').on('keyup', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseFloat(t, 10);
var a = $(this).attr("id"); // the textbox you write in
for (pp in id) {
if (t !== '' ) {
if(a != pp){ // make changes to any textbox except the one you write in
$("#" + pp).val(v / id[pp] * i);
}
} else {
$(".bx").val('');
}
}
});
$('input.bx').on('blur', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = Number(t, 10);
for (pp in id) {
if (t !== '') {
$("#" + pp).val(parseFloat(v / id[pp] * i));
} else {
$(".bx").val('');
}
}
});

Categories

Resources