Home > Enterprise >  How to disbale line breaks in textarea on focus
How to disbale line breaks in textarea on focus

Time:04-22

So I have a textbox(input) and I have added a functionality to it that if the user presses enter, the focus shifts to a textarea element. But for some reason, a line break gets added after focus on the textarea and the cursor appears. I tried using (keydown.enter)="$event.preventDefault()" on the textarea but it only prevents line breaks when the cursor is in the textarea. How do I ensure line breaks are not added into the textarea on focus?

CodePudding user response:

Hope I understand your requirements exactly.

Two things we need to achieve for your requirement.

1, disabled press enter in textarea

$('textarea').keypress(function(e){
    if ( e.which == 13 ) e.preventDefault();
});

2, fire press shift key, we implement by focus next element

$("#next_element").focus();

final code like below

$('textarea').keypress(function(e){
    if ( e.which == 13 ){
        $("#next_element").focus();
        e.preventDefault();
    }
});
<html>
    <head>
        <title>Textarea</title>
    </head>
    <body>
        <form action="javascript:void(0);" method="post">
            <textarea name="description" placeholder="Description" required></textarea>
            <input type="text" id="next_element" placeholder="Next element" required />
            <input type="submit" />
        </form>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>        
    </body>
</html>

  • Related