I have the following HTML code:
<fieldset>
<legend><span>Contact Details</span> <span class="edit1">Edit</span><span class="hide1">Hide</span></legend>
<div>
<!--content-->
</div>
</fieldset>
<fieldset>
<legend><span>Contact Details</span> <span class="edit2">Edit</span><span class="hide2">Hide</span></legend>
<div>
<!--content-->
</div>
</fieldset>
The spans with the class “hide1” and “hide2” are set to display:none on page load.
Within this code, using jQuery, I am trying to do the following:
- if edit1 is clicked on, this span becomes hidden, and the associated span with the class “hide1” becomes visible.
- This should be the same for all other spans in the code e.g. edit2 and hide2. Also if I want to add further edit and hide classes, the function should be able to handle this too e.g. edit3 and hide3 and so on.
So far, I have been able to find the edit span that is clicked on and hide it. I am struggling to get the associated “hide” class. Can anyone help me do this please? Here is my jQuery function so far:
var spans = $("#myIntForm").find("span[class^='edit'],span[class^='hide']");
spans.click(function() {
var $this = $(this);
spans.filter("span[class^='hide']").hide();
if($this.attr('class').substr(0,4)=='edit')
{
var visible = $this.filter("span[class^='"+$this.attr('class').substr(0,4)+"']");
visible.hide();
//find the class 'hide' with same ending number as class 'edit' and display it.
var invisible;
}
});
I’ve done something similar before, it was easier for me to delimit the classname in some way – i.e an underscore, and also using an ID to help with selecting like so:
Then you can find the associated classes like this:
I haven’t tested this but you get the idea.
One other point is that I think you don’t need to assign $(this) to a var, I don’t see anything in your code that would warrant that.
Hope this helps
EDIT: Forgot to hide the edit div on click, code updated
2nd EDIT: Woops, missed a close bracket, also needed a +1 on the substring 🙂 works fine now – got an example up here:
http://jsfiddle.net/rYMtq/
A bit irrelevant now that you got an answer but an unclosed bracket is enough to keep me awake at night 😀