$(this).val() not working in FireFox but works in Chrome - javascript

This is my problem. When I try to set the value of an input field in FireFox nothing happens. I don't get any errors. It simply just doesn't work. It is supposed to add two decimal places after the number. It works perfectly in Chrome. Here's my jQuery code...
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="$0.00" />
I've tried using $(this).attr('value' n); but that doesn't work either.

So, it does "work", but Firefox simply formats the number differently, it truncates the 0s. If you do
$(this).val(6.00);
you will see that it shows 6.
If you do
$(this).val(6.50);
it will show 6.5 but also an error that it is not a valid value.
What's with the error?
The default step value of the input is 1 which makes Firefox only consider numbers as valid that are a multiples of that.
If you set step="0.01" then Firefox considers floating point numbers as valid.
But the formatting is still incorrect
However, this still won't show the decimals for whole numbers. I guess that's just how it is given that the spec doesn't seem to describe how the value should be formatted.
If the format is more important to you than the functionality of the number input, use a normal text input instead.

This has to do with how firefox treats the number input type. https://bugzilla.mozilla.org/show_bug.cgi?id=1003896
You can try text if that is an acceptable input type for you.
Having found the above citation everything below is only interesting but not useful
For example in Firefox vs Chrome check out
http://jsbin.com/coyuyipeca/edit?html,js,output
You'll see the value is indeed formatted correctly in the alert in FF but lost when pushed to the number field. Change the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="text" placeholder="$0.00" />
and you'll see it work. Of course you will lose the benefits of the number field (notably mobile inputs) so it depends on how important that functionality is to you.
Note: One odd thing I note is if you set the input to
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" step=".01" placeholder="$0.00" />
You can use the increment button and get decimals, it only seems to be lost when jQuery sets the value. Not sure if this is an issue with jQuery or with FF

This seems to work for me in the following jsfiddle:
<input tabindex="1" class="drawer f-right m-left w50 right-text" type="number" placeholder="0.00" />
$('input.drawer').on('blur', function() {
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).val(n);
});
Which is your exact code. The only thing is you cannot input '$' symbol into a number field. That would fail. So for eg: '3.4512' gets truncated to '3.45' and set properly, but '$3.4512' just gets cleared when I try it.
https://jsfiddle.net/bz0os3kp/1/
Your code seems to work. It does truncate the trailing zeros in firefox however.

I found a work around that seems to work in Firefox. I change the type of input to number on focus giving me the proper keypad on mobile but then change the type back to text on blur giving me to two decimal places. See the code below...
$('input.drawer').on('blur', function(){
var number = parseFloat($(this).val());
var n = number.toFixed(2);
$(this).attr('type','text');
$(this).val(n);
});
$('input.drawer').on('focus', function(){
$(this).attr('type','number');
});

Related

jQuery replace with regex not working correctly

I want to exclude all characters which are not a digit or minus.
What strikes me is that I cannot start with a minus or enter it anywhere. Only after digits and using the keyboard arrow button is entering a minus possible.
What I would like is being able to just enter -60 or something the like.
What should I change?
$('.minus').keyup(function() {
var txt = $(this).val();
var nwtxt = txt.replace(/[^\d-]/ig, "");
$(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus">
Instead of using input type number use text
I think it's some kind of browser defence meganism that whenever you insert something that is not a number inside a number input field and you request the value from it, it will simply be null/undefined. On type="text" it looks like this is fine.
Also note your cursor is always put at the end of the text, because you replace the text always. So you can't insert a - (dash) before a number with only keyboard interaction. and a dash anywhere but in front of a number is invalid!
You can try to type in -60 in the number field as well but you first need to insert. 60 and then the minus character.
also its better to use $('.minus').input( instead of keyUp, since you can use the mouse to insert values as well (and the scroll wheel).
$('.minus').keyup(function() {
var txt = $(this).val();
console.log("value i got:",txt); //i added this logging to see that you didn't get anything on number.
var nwtxt = txt.replace(/[^\d-]/ig, "");
if(nwtext !==txt) //add this if statement so your cursor does not constantly jump to the end!
$(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus" placeholder="number">
<input type="text" maxlength="9" class="tekstvakjes minus" placeholder="text">

get number value from input element in JQuery not works when float parts empty

I want to code a currency converter, and only integer and float are allowed.So i detect the input change and do some calculation.
html snippet is as below:
<input type="number" id="currency">
JS is:
$("#currency").on("input", function(e){
var value = this.value
console.log(value)
});
Everything works well except when input is "12.", the value is an empty string?
what i want is 12 actually. How to solve the issue? Any help would be appreciated.
JSfiddle of snippet
This is because you are using input type="number"which wont allow any input other than number(including floating numbers).
But you put string or char as input you will see empty log statement and on doing parseInt(this.value) it will log NaN.
So if you still want to give string/number as a input you can use input type="text"
<input type="text" id="currency">
Input type="number" means any number including float, integer and does not allow to enter text.
so the best solution might be Input type="text" and if you want precision you can get by toFixed method as below example
$("#currency").on("input", function(e){
var value = this.value
if(isNumeric(value)){
alert(parseInt(value));
}
else{
alert("text")
}
});
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="currency">
Your issue is related to your localization.
As everybody confirms, <input type="number"> allows to enter integers and float.
So when typing 12., why do you get an empty result while some others get 12?
Because their decimal point is dot, while yours is something else!
E.g.: on my own system, where decimal point is comma, I get an empty result when typing 12. and 12 when typing 12,.

How to display input value of html number input with exactly 2 digits?

I would like to have something like this:
<input id="seconds" type="number" value="0" min="0" max="59" />
The only thing I would like to add here is to always show the numbers as 2-digit numbers at all times (showing 0 as '00', 7 as '07' and 53 as '53').
I've looked for plenty of solutions on SO, but none really does the job for me. In particular, hooking up the onChange eventHandler or blur() in jQuery to alter the number doesn't seem to do the job for me (I'm guessing this is because of the min-max-validation which I'm using, but I'm not sure).
In the bigger scheme, I would like make a simple and easy-to-change time control, using number inputs to easily change the hours/minutes/seconds. Isn't there any standard thing I could use ? The HTML time controls don't seem to be supported in all major browsers....
Somethig like This?
$( document ).ready(function() {
$('#seconds').on('input', function() {
var n = $(this).val();
if(n<10){
$(this).val(0+""+n);
}
});
});

Get value of <input type="number"> with JS when it contains non-numeric characters

This jsfiddle demonstrates the following issue.
The simplest example is:
<input id="number" type="number" value="1">
console.log(document.getElementById('number').value);
This logs 1 as expected. THIS however:
<input id="number" type="number" value="1A">
console.log(document.getElementById('number').value);
Just logs an empty string '', because of the non-numeric character in the value. Some devices+browsers (e.g. Chrome) allow you to enter non-numeric characters in these inputs.
This is annoying because I want the type="number" input for devices that support it (e.g. iPhone, iPad number keyboard). However I want to use javascript to stop dirty input from being entered - which requires fetching the value on keyup - then regex replacing the non-numeric chars.
It appears jQuery's .val() method gives the same result.
This is what I was looking for:
$('input[type=number]').keypress(function(e) {
if (!String.fromCharCode(e.keyCode).match(/[0-9\.]/)) {
return false;
}
});
I understand preventing user input can be annoying and this still allows invalid input such as 1.2.3
However in this situation it is exactly what I needed. Hopefully it will be of use to someone else. Thanks to #int32_t for the suggestion.
You're not supposed to use <input type=number> for things that are not numbers (in very mathematical senseā€”it won't work for phone numbers or zip codes either) and clearing of the value is deliberate.
You can test whether device supports type=number and attach your fallback only if it doesn't:
var input = document.createElement('input');
input.setAttribute('type','number');
if (input.type != 'number') { // JS property won't reflect DOM attribute
polyfill_number();
}
Alternatively (especially if your number is a zip code, serial number, etc.) you can use:
<input type=text pattern="[0-9]*">
and this will change the keyboard too.

getting not a number(NaN) error html/js

I am getting NaN error while clicking radio button first. The page have a3 radio button when I click that 1st button it saya NaN and remaining 2 buttons has no response
this is my HTML
<input type="hidden" name="totalamount" id="totalamount" value="<?php echo get_total_amount();?>" /
<input type="radio" name="rmr" id="payment1" value="3" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment2" value="5.5" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment4" value="10" onclick="updatepayment(this.value)" />
<div id="finalamount">
</div>
also I have mentioned my JS
$(document).ready(function(){
$('input[name=rmr]').click(function () {
//make sure one is checked
if($('input[name=rmr]:checked').length > 0) {
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
}
});
});
Three things:
1) As you're using the amount from the "totalamount" element, one has to ask: Are you sure that
value="<?php echo get_total_amount();?>"
...is outputting a valid number? Because if not, then the code
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
...will indeed result in NaN. The * operator will try to convert both of its operands from strings to numbers, and of course if the value output by that PHP code isn't a valid number (for instance, if it's "$0.00" or something), the result of the conversion will be NaN. And NaN times anything is NaN.
This example of an invalid amount in the "totalamount" element yields something that looks a lot like the behavior you describe. (That code isn't identical to yours, I did some very light refactoring, see below. But for the purposes of demoing an invalid number, it doesn't matter.)
2) There's no > at the end of that hidden input in the text of your question. If you did a direct copy-and-paste, I wonder if that could be the problem?
3) As you're using jQuery, there's no need for the onclick attributes. Instead:
$(document).ready(function(){
$("input[name=rmr]").click(function(){
var checked = $("input[name=rmr]:checked");
updatePayment(this.value);
if (checked.length > 0) { // make sure one is checked
{
$("#finalamount").html( $("#totalamount").val() * checked.val() );
}
});
});
...assuming you want updatePayment called every time.
Live example
Folding updatePayment into the main click behavior lets you avoid any issues that may exist with the order in which DOM0 (onclick attribute) handlers and DOM2 handlers (the ones used with jQuery) are called.
It is working fine for me. Please find the working code in jsfiddle. You have to make sure that the value in the totalamount input is a numeric value. You can user parseFloat() to convert the string value into a float value.
Ex
parseFloat($("#totalamount").val()) * $("input[name=rmr]:checked").val()
As #Crowder parseFloat() is not necessary since javascript take care of the type conversions.
You try to put an alert()/console.log() command before the calculation to see whether the totalAmount is having an non-numeric value. Ex: alert($("#totalamount").val())

Categories