Sara Ree
Sara Ree

Reputation: 3543

jQuery .focus() doesn't work for the textarea

I want to focus on the textarea using jquery, so I wrote this:

let item = $('[data-model-abs-id="_player.5p6G3xVhKxa.6pN08IGqVGe.6dzqtCIQ2y4.6dkh6UeayIM"]');
item.focus();

It didn't work, so I tested if the textarea is selected or not:

let item = $('[data-model-abs-id="_player.5p6G3xVhKxa.6pN08IGqVGe.6dzqtCIQ2y4.6dkh6UeayIM"]');
item.animate({'top': '-=50px'},'slow');

The text input moves, so I think I selected the textarea correctly and at the right point.

I tested item.get(0).focus(); and setTimeout and setInterval to initiate the focus but none of them worked.

Here is the last thing I tested (I'm using Chrome):

let interval = setInterval(focusEachSecond, 1000); // also setTimeout doesn't work

function focusEachSecond(){
  var item = $('[data-model-abs-id="_player.5p6G3xVhKxa.6pN08IGqVGe.6dzqtCIQ2y4.6dkh6UeayIM"]')
  item.focus()
}

Here is textarea tag:

<textarea style="font-family: &quot;Calibri Light Charset0_87E9C737&quot;, sans-serif; font-size: 26.9764px; line-height: normal; font-weight: normal; direction: ltr; text-align: left; color: rgb(255, 0, 0); padding: 1.47144px 2.4524px 0px; height: 34.3146px; transform: translate(0px, 0px);" maxlength="" data-accepts="events" placeholder="" data-reactid=".0.0.3.2.0.1.0:$_player=15p6G3xVhKxa=16pN08IGqVGe.0.3:$c803.1:$c993.$slideobject1275.2.0"></textarea>

What I'm missing and How to fix this?

Upvotes: 0

Views: 54

Answers (1)

Mamun
Mamun

Reputation: 68933

.get() returns an array of raw DOM elements. .eq() returns it as a jQuery object, meaning the DOM element is wrapped in the jQuery wrapper.

Try using .eq().

item.eq(0).focus();

Demo:

//$("li").get(0).addClass('myClass1');//Uncaught TypeError: $(...).get(...).addClass is not a function
$("li").eq(1).addClass('myClass2');
.myClass1{
  color: red;
}
.myClass2{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
</ul>

Upvotes: 1

Related Questions