0

I am trying to focus on a textarea in my HTML. The textarea has a function to submit on enter.

<form id = "msgform"  method="POST" >
    {% csrf_token %}
        <textarea  id = "msg" name = "msg" > </textarea>
           
</form>

I have a function that focuses on the textarea on page load, and I want to do the same when my ajax call returns success

$.ajax({
  type:'POST',
  url:'{{request.path}}',
  data:{
    value:$('#msg').val(),
    csrfmiddlewaretoken: '{{ csrf_token }}',
  },
  
  success:function(data){  
   
    $( "#Wrap" ).load(window.location.href + " #M" );

    ('#msg').focus()
    
  }

})

The rest of the Ajax call works fine, but the ('#msg').focus() does not work. What could be causing this?

1 Answers1

0

('#msg').focus() should be $('#msg').focus()

PS: besides the above, the problem might also to lie in the part of the code you did not provided, and that's the Submit function

Use: Event.preventDefault() - Web APIs | MDN

A button inside a form that is not of type="button" by default triggers a form Submit Event and the browser usually follows the form's action URI and/or does a page refresh (visible usually with the tab spinner, or i.e: inside Dev Tools Network)

To prevent that behavior use

$("#msgform").on("submit", function(event) {
    event.preventDefault();

    // AJAX HERE
});
Roko C. Buljan
  • 164,703
  • 32
  • 260
  • 278
  • This is not the problem because the textarea actually uses a different way to submit, and everything else in the ajax call works. – Jackie Soussan Jun 28 '20 at 23:07