www.webdeveloper.com
Results 1 to 2 of 2

Thread: Selecting text from box that was clicked

  1. #1
    Join Date
    Jun 2007
    Location
    England
    Posts
    448

    Question Selecting text from box that was clicked

    Hi guys, i currently have a page which has lots of boxes with different data in them like this:

    HTML Code:
    <div class="box">
                    
            <div class="box_name">
             Test Name
             </div>
    
            <div class="time">
                12:45
            </div>
                        
            <div class="message">
            A message 
             </div>
    
    
    <a href="#" id="button">View Content</a>
    
    </div>
    and i want to grab the value which is inside the time class div and pass it to the popup box.
    currently this gets the value:

    PHP Code:
    $('#button').click(function() {


                var 
    time = $('.time').html(); 
    but because the .time class is used on each box it always passes the content from the first box on the page.

    is there no way to implement "$this" into the function so it gets the time value only from the box which was clicked.
    im stuck.

    hope that made sence

    David

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    There is! The closest() function will traverse upwards through the parents until specified element is found. If you change the button ID to a button class this code will work:
    Code:
    $('.button').click(function(){
    	var box = $(this).closest('.box'); // get's the box the button is in
    	var time = $('.time', box).text(); // finds the .time element in the box
    New to web development or in need of a good reference? Check out the Mozilla Developer Network or W3Schools.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles