k25
k25

Reputation: 407

jQuery - Selecting a text box before a span tag with certain CSS class

I am a beginner in jQuery. It would be great if somebody could help me with this. I am not sure what's going wrong here.

This is what I am trying. I have a element with class as "spanClass1". Before this element there is another element and a text box element. My requirement is to scroll to that text box element and gain focus to the element. And also I added some css to see the change happening. But the problem is that the code above doesn't seem to be working. If I replace the selector in .prev(..) to 'span', it works. Am I missing something? It would be really helpful if somebody could help me with this.

<html><br />
&lt;head&gt;<br />
&lt;title&gt;<br />jQuery&lt;/title&gt;<br />
&lt;script type="text/javascript" language="javascript" src="jquery.js"&gt;<br />&lt;/script&gt;<br />
&lt;script type="text/javascript" language="javascript"&gt;<br />
 $(document).ready(function() {<br />
  var elem = $('.spanClass1').get();<br />
  alert(elem.length);<br />
  alert("Text box elements " + $('input[type=text]').get().length);<br />
  if (elem.length &gt; 0)<br />
  {<br />
   var elem1 = $(elem[0]).prev('input[type=text]');<br />
   $(this).scrollTop($(elem1).position().top);<br />
   $(elem1).css('background-color','red');<br />
   $(elem1).focus();<br />
  }<br />
  });<br />
&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
 &lt;br /&gt;<br />
 &lt;div&gt;<br />
 &lt;input type="text" id="text1" value="test" class="selected"&gt;<br />&lt;span id="elem4" class="sClass1"&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/span&gt;<br />&lt;span id="elem5" class="spanClass1"&gt;<br />This is a test&lt;/span&gt;<br />&lt;br /&gt;<br />
 &lt;/div&gt;<br />
&lt;/body&gt;<br />
</html>

Thanks in advance.

Regards, Karthik

Upvotes: 0

Views: 1380

Answers (2)

Vishal Seth
Vishal Seth

Reputation: 5048

You need to use .prevAll() instead of .prev()

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37813

The call .prev() returns only the previous element, not other elements that come before it.

You want the .prevAll() call:

var elem1 = $(elem[0]).prevAll('input[type=text]');

Upvotes: 2

Related Questions