SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Change name of a link after user clicks on it

    I would like to change the text of an <a> element when the user clicks on it. The code that I've written is only "half" working:

    Code:
    $('#linkid').click(function() {
    	if ($('#linkid:contains("text1")')) {
    		$('#linkid').html('text2');
    	} else {
    		$('#linkid').html('text1');
    	}
    .
    .
    .
    Initially the text of the <a> element is "text1".

    When I click on it the text is correctly changed to "text2". But if I click on it again, the text doesn't change back to "text1", it remains "text2".

    What am I doing wrong?

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Hi,

    Try doing it like this:
    Code:
    $('#linkid').click(function() {
      this.innerHTML = (this.innerHTML == 'text1') ? 'text2': 'text1';
    });
    It sounds like the condition is always true, try alerting to see what's returned.
    Code:
    $('#linkid').click(function() {
      alert($('#linkid:contains("text1")'));
    }
    You want to prevent the amount of lookups using the $() function in your code.
    Get an element with it once, then test what you want against it.

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,701
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements.
    So, in the if condition, you need to check that the length of the jQuery object is greater than 0, to ensure that you properly catch a failed match.

    However, there is a less expensive and possibly more readable way to perform the check, and that is to test the html content of the element itself.
    $('#linkid').html() === 'link1'

    You can also use the this keyword in the function to refer to the clicked link, so your code could instead look like this:

    Code javascript:
    $('#linkid').click(function() {
        if ($(this).html() === 'text1') {
            $(this).html('text2');
        } else {
            $(this).html('text1');
        }
        ...
    });

    You could also use a ternary operator to specify what content to use.


    Code javascript:
    $('#linkid').click(function() {
        var linkText = ($(this).html() === 'text1') ? 'text2' : 'text1';
        $(this).html(linkText);
        ...
    });
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by markbrown4 View Post
    Hi,

    Try doing it like this:
    Code:
    $('#linkid').click(function() {
      this.innerHTML = (this.innerHTML == 'text1') ? 'text2': 'text1';
    });
    It sounds like the condition is always true, try alerting to see what's returned.
    Code:
    $('#linkid').click(function() {
      alert($('#linkid:contains("text1")'));
    }
    You want to prevent the amount of lookups using the $() function in your code.
    Get an element with it once, then test what you want against it.
    Thank you

    Quote Originally Posted by paul_wilkins View Post
    The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements.
    So, in the if condition, you need to check that the length of the jQuery object is greater than 0, to ensure that you properly catch a failed match.

    However, there is a less expensive and possibly more readable way to perform the check, and that is to test the html content of the element itself.
    $('#linkid').html() === 'link1'

    You can also use the this keyword in the function to refer to the clicked link, so your code could instead look like this:

    Code javascript:
    $('#linkid').click(function() {
        if ($(this).html() === 'text1') {
            $(this).html('text2');
        } else {
            $(this).html('text1');
        }
        ...
    });

    You could also use a ternary operator to specify what content to use.


    Code javascript:
    $('#linkid').click(function() {
        var linkText = ($(this).html() === 'text1') ? 'text2' : 'text1';
        $(this).html(linkText);
        ...
    });
    Thank you, it worked

    I have just one question: you wrote that "The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements." You mean :contains?

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,701
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by D3V4 View Post
    I have just one question: you wrote that "The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements." You mean :contains?
    I mean:
    $('#linkid:contains("text1")')

    Even testing just $('#garbage') when no garbage identifier exists would test as true, because $() doesn't return an array, it returns an object.
    And we all know that javascript compares objects in strange ways.
    Some info about that is:
    If an object is compared with a number or string, JavaScript attempts to return the default value for the object.

    Code javascript:
    $('#garbage').toString() // [object Object]
    [].toString() // ""

    jQuery also formalised their empty sets in 1.4
    jQuery() – jQuery API
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    I mean:
    $('#linkid:contains("text1")')

    Even testing just $('#garbage') when no garbage identifier exists would test as true, because $() doesn't return an array, it returns an object.
    And we all know that javascript compares objects in strange ways.
    Some info about that is:
    If an object is compared with a number or string, JavaScript attempts to return the default value for the object.

    Code javascript:
    $('#garbage').toString() // [object Object]
    [].toString() // ""

    jQuery also formalised their empty sets in 1.4
    jQuery() jQuery API
    Understood


Bookmarks

Posting Permissions

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