Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    glz
    glz is offline
    New Coder
    Join Date
    Apr 2007
    Posts
    57
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question I want to detect linebreak char in text input

    Code:
    function detectNL(elem) {
    	var lastChar = elem.value.substr(elem.value.length-1,1);
    	if (lastChar == "\r\n") {
    		alert("detected nl char");
    	}
    }
    here is the form element:
    Code:
    <form name="form">
    <input type="text" name="testField" value="" onkeyup="detectNL(document.form.testField);" />
    </form>
    Basically I want to detect when the enter button is pressed or when a linebreak character is typed into the field. (how you ask a linebreak character can be manually type? well you can paste on in with ctrl v)
    Above is my attempt

    1. I'm not really sure how to detect the character at all in JS, I know windows linbreaks are \r\n
    linux \n
    mac \r
    2. Maybe I need to detect the keystroke event on the field? I have no idea how to do this as well..
    3. The text field won't let you press enter at all, it will switch focus or try to submit form.. etc.. if you press the enter button, so I suppose detecting the keys pressed while the focus is on that element is necessary in order to detect when the enter key is pressed....

    Above is my attempt, I just want to see a solution to my above description, you can stray from my original attempt if you like...
    Thank you.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    <script type = "text/javascript">

    document.onkeyup = function(ev) {
    var key;
    ev = ev || event;
    key = ev.keyCode;
    if (key == 13) {
    alert ("Newline detected");
    }
    }

    </script>


  •  

    Posting Permissions

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