/    Sign up×
Community /Pin to ProfileBookmark

show div on click

Hi, I need javascript (jquery) to show a matching div when a radio button is selected (radio buttons are not a necessity, but it needs to be done in a form in order to pass the choice to php). Also, the input circles need to be hidden, so I’m using labels.

[CODE]
<form>
<input type=”radio” name=”what” value=”1″ id=”1″><label for=”1″>jen</label>
<input type=”radio” name=”what” value=”2″ id=”2″><label for=”2″>dva</label>
<input type=”radio” name=”what” value=”3″ id=”3″><label for=”3″>tri</label>
</form>

<div id=”divToShow1″>…</div>
<div id=”divToShow2″>…</div>
<div id=”divToShow3″>…</div>
[/CODE]

To make things even easier, the selected label gets a unique class when clicked (however, I was unable to select it directly, and I see this as the simplest of solutions, something like – var i=$(‘.alive label’).id ):

[CODE]
$(‘label’).click(function(event)
{
$(‘label’).removeClass().not(this).addClass(‘dead’);
$(this).addClass(‘alive’);
});
[/CODE]

I tried adding the following lines to the above chunk of javascript:

[CODE]
var radio=document.getElementsByTagName(‘input’);
for(var i=0; i<radio.length; i++)
{
if (radio[i].checked)
alert(i+1);
}
[/CODE]

And the first click works like a charm, however, every click after it displays two alerts – first being a repeat of the previous, followed by the correct one. (for example, you press the third label and you get alert(3), then you press the first and you get alert(3) alert(1). I believe it is due to the class switching, or some sort of a delay related to it. I even tried separating the above code from the class switching piece, but with the same resaults.)

Please note that the input IDs are 1,2,3 for divsToShow 1,2,3 so the number alert above is all I need.

I know very little about javascript or jquery, but I think this should be a piece of cake. Thanks

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @janje spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...