1

I have a form with an input such as

<td class="units_depth_form">
  <input id="id_form-0-rain" name="form-0-rain" step="0.01" type="number" />
</td>

and I want to allow a user to enter units. For instance the form could expect values in inches, but I would allow a user to enter '20 cm', and when leaving the text box it would contain '7.87'.

To do this I have in the JavaScript part of the page the following jQuery code:

$(".units_temp_form input").focusout(function() {
    // Convert and replace if valid double ending with 'cm'

and I added 'novalidate' at the end of the form tag. The problem is that $(this).val() is empty when the input is invalid. Is there another way to get to the user entered value?

Before anyone suggests the solution, removing the type='number' part would solve the problem but I'd prefer not to do this. This form is created in Django through a ModelForm, and it would involve a lot of hacking that would defeat the purpose of using Django in the first place.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Alain
  • 532
  • 6
  • 15
  • Perhaps you could take out all `type='number'` when the document is ready, and place them back when form is submitted. – Marcos Dimitrio Jun 17 '15 at 01:49
  • Thanks for the suggestion. It would solve the problem, but the form also has a 'step' attribute which instructs the form to display up and down arrows in the input box to increase or decrease the value by the given step. Removing the 'type' attribute also removes these arrows. It would be nice to be able to keep them. – Alain Jun 17 '15 at 02:02

1 Answers1

0

That seems to be the way browsers behave when they find invalid data inside a type="number" input.

Perhaps your best option is to use <input type="text"/> and implement the up and down arrows yourself. There are several options around, I found one that looks nice and another that keeps going on mouse down.

If the form inputs must be created with type="number" because of Django, you can change that on the client as soon as the page loads:

$(document).ready(function() {
    $(".units_temp_form input").each(function(){
        if ($(this).attr('type') == "number") {
            $(this).attr('type', 'text');
        }
    });
});
Community
  • 1
  • 1
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
  • I had come to the same conclusion last night from this [discussion](http://stackoverflow.com/questions/18852244/how-to-get-the-raw-value-an-input-type-number-field). Thanks for the links to the other options. – Alain Jun 17 '15 at 10:07