admin管理员组

文章数量:1397156

I have a number input that I want to hold integers. If the value gets set to negative then I want the symbol shown to be ∞ (∞).

Doing this doesn't work (a blank is shown instead of "∞"):

<%
if foo <= -1
    v = '&#8734;'
else
    v = foo
end
%>
<input type="number" value="<%= v %>">

Is there a way to do it without resorting to javascript?

I have a number input that I want to hold integers. If the value gets set to negative then I want the symbol shown to be ∞ (&#8734;).

Doing this doesn't work (a blank is shown instead of "∞"):

<%
if foo <= -1
    v = '&#8734;'
else
    v = foo
end
%>
<input type="number" value="<%= v %>">

Is there a way to do it without resorting to javascript?

Share Improve this question asked Apr 3, 2014 at 17:22 eraperterapert 1,41312 silver badges15 bronze badges 5
  • <input type="number" value="&#8734;"> works for me – juvian Commented Apr 3, 2014 at 17:24
  • @juvian and what browser would that be? – epascarello Commented Apr 3, 2014 at 17:25
  • Firefox. Just tried in chrome and it stays blank as you say – juvian Commented Apr 3, 2014 at 17:26
  • Do you need the input to be type number? Would work if you set it to string – juvian Commented Apr 3, 2014 at 17:27
  • FF 28 simply displays '&#8734;' as a string in the input field. Chrome is blank, yes. Setting value to '1234' as a string sets the value appropriately on both browsers. juvian, your solution works but only on FF and only if the code is entered into the value field directly (string doesn't work). I need a solution that works for Chrome though. – erapert Commented Apr 3, 2014 at 17:37
Add a ment  | 

3 Answers 3

Reset to default 2

What are your requirements for having a "number" field? Can you rely on form validation and use Javascript to progressively enhance just typing numbers. Then use something like this

<input type="text" pattern="([0-9]|&#8734;)+">

(pattern will prevent the form from submitting unless it's a number or infinity symbol)

You need to use type text for this field and convert infinity sign using CGI::unescapeHTML

<% 
   if foo <= -1
     v = CGI::unescapeHTML('&#8734;')
   else
     v = foo
   end
%>
<input type="text" value="<%= v %>">

this question is a bit old, but if anyone else has the same problem, this was my solution, it's a bit janky, but it works:

<input type="text" id="myInput" value="&#8734">

<script>
document.getElementById("myInput").addEventListener("focus", (e) => {
    e.target.type = "number";
});
document.getElementById("myInput").addEventListener("blur", (e) => {
    if(e.target.value == 0 || isNaN(e.target.value)){
        e.target.type = "text";
        e.target.value = "∞";
    }
});
</script>

You can check a codepen here

The good thing about this approach is that the user can still use the arrows to increase/decrease the number, since the type is still "number"

本文标签: javascriptHTML how to set value of ltinput typequotnumberquotgt to infinityStack Overflow