How to switch innerHTML between two alternative lines using jQuery

I have a span element that I want to switch between the words "Price" and "No", onclick another element.

Essentially, you need to check the existing contents of the cells to see what is currently present, and then replace it with another.

Something like that:

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

I compiled the toggleHTML method used above to show how I expect it to work.

+4
source share
4 answers

You can use the html or text method 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; }); } 

Using:

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

http://jsfiddle.net/AyFvm/

+8
source

You can do something like this:

 var html = $('#element2').html(); html = html.indexOf('Price') > -1 ? "Net" : "Price"; $('#element2').html(html) 
+1
source

try it

HTML

 <input type = "checkbox" name = "element1" id="input1"> 

JQuery

 $('#input1').click(function(){ $('#element2').text(function(){ return $('#element2').text()=="Price" ?"Net":"Price" ; }); }); 

avoid using inline javascript ...

the violin is here

+1
source

this is the code: html:

 <input type = "checkbox" name = "element1" id="element1"> 

Javascript:



 $(document).ready(function() { $("#element1").click(function() { if($("#element2").html() == "Price") $("#element2").html("Net"); else $("#element2").html("Price"); }); }); 

code>
0
source

Source: https://habr.com/ru/post/1480711/


All Articles