SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2010
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    checking if a textbox is selected

    heys all, i'm trying to restrict user input to only 3 digits (3 numbers iow)

    so what i've did is to check the onkeydown and check if they are digits and if input.value text length is 3 or more i will cancel it.

    However, if the user had words selected in the textbox, i will wish to allow input. Because imagine the user selected the string "123" in the textbox, and wishes to override this string by typing a new number. but with my current logic, since the textbox already have 3 digits, he had his input rejected, which is not what i would want.

    is there a workaround?

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Why don't you just use the maxlength attribute?

    HTML Code:
    <input type="text" maxlength="3">

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2010
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    lol i've forgotten about that.

    but other than that, there is no way to check if text has been selected within the textbox right?

  4. #4
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Yes, there is, but it's complex because IE and decent browsers have different ways of going about it. In Firefox, Safari and Opera it would be very simple:

    Code:
    var selectedText = inp.selectionEnd - inp.selectionStart > 0;
    where inp is a reference to the text box. The selectedText var would be true or false, indicating if text was selected. IE requires you to use document.selection and follow a roundabout way of finding the length of the selected text.

    But from what you describe, it seems like maxlength will do what you want.

  5. #5
    SitePoint Enthusiast
    Join Date
    Aug 2010
    Posts
    51
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hey thanks for the reply. i may need this in the future for other more complex requirements


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •