I have several buttons. When clicked I would like to remove all classes from my text field.
Currently this is what I have, but the code is not optimized.
var maintextarea = $('.myTextArea');
$('#styleBtn1').click(function(){
maintextarea.removeClass('fromStyleBtn2 fromStyleBtn3');
maintextarea.addClass('fromStyleBtn1');
return false;
});
$('#styleBtn2').click(function(){
maintextarea.removeClass('fromStyleBtn1 fromStyleBtn3');
maintextarea.addClass('fromStyleBtn2');
return false;
});
$('#styleBtn3').click(function(){
maintextarea.removeClass('fromStyleBtn1 fromStyleBtn2');
maintextarea.addClass('fromStyleBtn3');
return false;
});
Question: How can I rewrite the removeClass portion so that when a button is clicked all previous classes will be nulled and my class gets added?
You can simply using the method chaining
calling removeClass() without any parameter will remove all classes.
EDIT : Your entire code can be replaced like this generic form.. Assuming your class name will always in the format “from”+elementID. (Ex : fromStyleBtn2)