Let's say you have a .click()
call. What code could you write inside of that .click()
call so that each time you click the selected element, you change the text between two strings. I'm assuming .toggle()
and .text()
would play a role here...
Let's say you have a .click()
call. What code could you write inside of that .click()
call so that each time you click the selected element, you change the text between two strings. I'm assuming .toggle()
and .text()
would play a role here...
- what two strings? what are texts? – Kon Commented Apr 7, 2011 at 3:19
- I don't think what the actual strings are matters.... – Justin Meltzer Commented Apr 7, 2011 at 3:21
- Oh, nevermind.. I just figured out what you meant. – Kon Commented Apr 7, 2011 at 3:29
4 Answers
Reset to default 26Try something along these lines:
$element.bind('click', function() {
$(this).html($(this).html() == 'string1' ? 'string2' : 'string1');
});
Edit - 2020-01-28
Note that bind()
is now deprecated. You should be using on()
instead, as of jQuery 1.7+:
$element.on('click', function() {
$(this).text((i, t) => t == 'string1' ? 'string2' : 'string1');
});
Say your clickableElement is a button and you want to toggle the button's text/label:
$('#clickableElement').click(function() {
var originalValue = $(this).val();
$(this).val(originalValue == 'string1' ? 'string2' : 'string1');
});
$('#togglep').on('click', function(){
$(this).text(function(st1,st2){
if (st2=='MARKO'){return 'POLO'};
return 'MARKO'
})
})
Try this:
$('#someElement').toggle(function(){
$(this).text('text1');
},
function(){
$(this).text('text2');
}
);