0

I have three input fields on my form that I have successfully created and limited to three digits only. I then want to test them when changed that they are less than 255 and if not take the user back to that field to try again. The code below is working except for the $(this).select(); option. How can I quickly take the user back to the 'offending' field?

            $(".colorField").change(function () {
            if (parseInt($(this).val(), 10) > 255) {
                $(this).select();
                //display error message
                $("#errmsg").html("Must be less than 255").show().fadeOut(2000);
            }
        });

1 Answer 1

1

You can use the .focus() event to set the focus back on your input.

Also, just using $(this).val().length will be enough to get the input value characters count.

Here is a working JSFiddle:
http://jsfiddle.net/3Qj7L/1/

HTML

<input type="text" class="colorField">
<div id="errmsg"></div>

JS

$(".colorField").change(function () {

    // Input value length should be less than 255 chars
    if ( $(this).val().length > 255 ) {
        // Set the focus back on the input
        $(this).focus();
        // Display error message
        $("#errmsg").html("Must be less than 255").show().fadeOut(2000);
    }
});

EDIT after comment

Here is a new jsFiddle that checks if the user's input is a digit, and if the number is less than or equal to 255. If it's higher, it will automatically replace the value by 255.
http://jsfiddle.net/3Qj7L/2/

HTML

<input type="text" class="colorField" maxlength="3">

JS

// Check if the number is less than or equal to 255
$(".colorField").keyup( function(e) {

    if ( $(this).val() > 255 ) {
        e.preventDefault();
        $(this).val(255);
    }
});

// Only accepts numbers
$(".colorField").keypress( function(e) {

    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        return false;
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

He's not trying to limit to 255 characters. He's trying to limit the input numeric value to a maximum of 255.
Thanks, misreading from me. I edited my answer and gave another option than what the author intended to do. I still answer his original question with the .focus() event.
Thank you everyone for your responses. Even the JSFiddle is not returning focus so now I think it may just be an IE11 issue. Thank you again as we now have a couple of work arounds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.