Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

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"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top