jQuery: If, Else with buttons error
Posted
by
Wipqozn
on Stack Overflow
See other posts from Stack Overflow
or by Wipqozn
Published on 2011-02-08T15:02:18Z
Indexed on
2011/02/08
15:25 UTC
Read the original article
Hit count: 226
I'm running into an odd error. I'm working in Django 1.2, and have implemented the commenting framework. I'm trying to attach a hide/show button to each comment field, but whenever click on a hide/show button, it behaves as if each hide/show button beneath it on the page was clicked. Here's the jQuery code:
<input type="Button" id="hideShow" name="hide/show" value="Hide"></input>
<script>
$("#hideShow").click(function() {
if($(this).val() == "Hide") {
$("textarea").hide("fast");
$(this).val("Show");
}
else {
$("textarea").show("fast");
$(this).val( "Hide");
}
});
</script>
So, when I click the Hide/show button, it will perform the action for each button beneath the clicked button + once for the button itself. So If I click a button, and there are two buttons beneath it, and value=hide it will first hide the 'textarea', than show the text area, than finally hide it again.
I'm new to jQuery (although I do have experience in other languages), and I have an -idea- why it's not working: that whenever an action is performed jQuery jumps to the first one, than continues down the page looking for any other actions performed, and responds to each one. So it comes to my first button, sets it as being clicked, and so when jQuery comes across the other buttons it views them all as being 'clicked' and performs actions accordingly.
I've thought of a semi-solution to my problem, putting in a variable which tracks how many times it has gone through, and than acting based on -that- action. But I would rather not do that, since it's not really a solution to the problem at hand but a work around. Any input is appreciated.
© Stack Overflow or respective owner