Reputation: 407
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 />
<head><br />
<title><br />jQuery</title><br />
<script type="text/javascript" language="javascript" src="jquery.js"><br /></script><br />
<script type="text/javascript" language="javascript"><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 > 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 />
</script><br />
</head><br />
<body><br />
<br /><br />
<div><br />
<input type="text" id="text1" value="test" class="selected"><br /><span id="elem4" class="sClass1"><br /> </span><br /><span id="elem5" class="spanClass1"><br />This is a test</span><br /><br /><br />
</div><br />
</body><br />
</html>
Thanks in advance.
Regards, Karthik
Upvotes: 0
Views: 1380
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