开发者

Get current value in a set of CSS classes using Jquery

I have some class like this

<div class = "student">
<div class = "name">Adam </div>
<input class = "paperTaken">
</div>

<div class = "student">
<div class = "name">Smith</div>
<input class = "paperTaken">
</div>

When I put the cusor on an input field (say, "paperTaken" in the first "student" class), I can get the corresponding value in class "name" (eg: Adam).

Could you help me? Thank you in advance.

P/S:

Actually I used it for autoComplete with the Jquery Autocomplete Plugin , so I must listen to paperTaken for autocomp开发者_StackOverflowlete

$(function(){ 
autoComplete(); 
} 

function autoComplete() { 
//This will result list of papers that StudentName take 
$(".paperTaken").autocomplete(baseUrl+"/autocomplete.php?student=StudentName 
... } 

I want to get the student name to put into the request for autocomplete. So I tried to apply your suggestion using

$('.paperTaken').focus(function() {
 ... 
} 

But it's seem that not work.

I'm wondering if the "papertaken" was already listened by autocomplete, can it listen to the "focus" call?


I assume you want to fill the input with the content of the element with class name? Then following might work (untested):

$('.paperTaken').focus(function(){
  $(this).val($(this).siblings('.name').text());
});


$('.paperTaken').focus(function() {
       // $(this) references the <input> element that received focus
       // .prev() references the sibling that comes directly before $(this)
       // .text() will return the text value of the .prev() element
    var name = $(this).prev().text();

      // Log the result to the console, or use it however you need
    console.log( name );
});

Relevant jQuery docs:

  • .prev() - http://api.jquery.com/prev/
  • .text() - http://api.jquery.com/text/


  1. List item

$(document).ready(function() {

    $('input.paperTaken').focus(function() {
        var value=$(this).siblings('.name').text();
        $(this).val(value);
    });

});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜