Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle innerHTML between 2 alternative strings using Jquery

Tags:

html

jquery

I have span element which I wish to toggle the contents of, between the words 'Price' and 'Net', onclick of another element.

Essentially, it needs to test the existing cell contents to see which is currently present and then swap it with the other.

Something like this:

<input
    type    = "checkbox"
    name    = "element1"
    onclick = "$(#element2).toggleHTML('Price', 'Net')">

<span id="element2">Price</span>

I made up the toggleHTML method used above to demonstrate how I expect it might work.

like image 955
Peter White Avatar asked Dec 27 '22 03:12

Peter White


1 Answers

You can use html or text method's callback function.

$('input[name="element1"]').click(function() {
    $('#element2').text(function(_, text) {
        return text === 'Price' ? 'Net' : 'Price';
    });
});

http://jsfiddle.net/BLPQJ/

You can also define a simple method:

$.fn.toggleHTML = function(a, b) {
    return this.html(function(_, html) {
        return $.trim(html) === a ? b : a;
    });
}

Usage:

$('#element2').toggleHTML('Price', 'Net');

http://jsfiddle.net/AyFvm/

like image 100
undefined Avatar answered May 25 '23 02:05

undefined