user3854015
user3854015

Reputation: 3

jQuery multiple objects select $(this)?

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);
            }
        });

Upvotes: 0

Views: 51

Answers (1)

Niflhel
Niflhel

Reputation: 663

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;
    }
});

Upvotes: 1

Related Questions