简体   繁体   中英

Firefox firing change event on input.attr(“type”, “number”)

I'm experiencing a problem, only in firefox, when an input is focused, and I change the input type from "text" to "number" , a change event is triggered and the input loses focus.

What I want to achieve is to change the input to a number field on focus, allow edit, and change the input toLocaleString() on blur.

Here are my codes:

 $("input").focusin(function() { $(this).val(toNumber($(this).val())); $(this).attr("type", "number"); }); $("input").focusout(function() { $(this).attr("type", "text"); $(this).val("$ " + toCost($(this).val())); }); // Added during edit to make code testable $('input').on('change', function(){ console.log('changed'); }) function parseNumber(value) { var result = parseFloat(toNumber(value)); if (!isNaN(result)) { return result; } return 0; } function toNumber(str) { return str.replace(/\\s/g, "").replace(/\\$/g, "").replace(/,/g, ""); } function toCost(number) { return parseNumber(number).toLocaleString(); } 
 <!-- Added during edit to make code testable --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input/> 

I can't figure out why in Firefox the input is triggering a change event and losing focus when I select it. It works the way I want it to when I try to use $("#myInput").focusin() on the console though.

It works fine on Chrome and Microsoft Edge.

Thanks in advance for taking a look at this!

I'm currently using this as a solution:

 function is_firefox() { return navigator.userAgent.search("Firefox") >= 0; } $("input").focusin(onFocusIn); $("input").focusout(onFocusOut); $('input').change(onInputChange); function onFocusIn() { $(this).val(toNumber($(this).val())); $(this).attr("type", "number"); // remove on 'change' and 'focusout', and add back after a short delay if (is_firefox()) { $(this).off("change"); $(this).off("focusout"); setTimeout(function(element){ element.change(onInputChange); element.focusout(onFocusOut); }, 15, $(this)); } } function onFocusOut() { $(this).attr("type", "text"); $(this).val("$ " + toCost($(this).val())); } function onInputChange() { console.log("changed"); } $("input").focusout(); function parseNumber(value) { var result = parseFloat(toNumber(value)); if (!isNaN(result)) { return result; } return 0; } function toNumber(str) { return str.replace(/\\s/g, "").replace(/\\$/g, "").replace(/,/g, ""); } function toCost(number) { return parseNumber(number).toLocaleString(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <input value="1000"/> 

I don't think it's the perfect solution, but it works for me now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM