Afshin
Afshin

Reputation: 2437

find out radio set`s default checked value on page load with jquery

I've written a jquery code which simply adds a style to divs.

$('input[type=radio][name=radio-set]').change(function() {
            if (this.id == 'first') {
                $("div.second, div.third").removeAttr('style');
                $("div.first").css({"opacity":"1"});
            }
            else if (this.id == 'second') {
                $("div.first, div.third").removeAttr('style');
                $("div.second").css({"opacity":"1"});
            }
            else if (this.id == 'third') {
                $("div.first, div.second").removeAttr('style');
                $("div.third").css({"opacity":"1"});
            }

        });

<input id="first" type="radio" name="radio-set" checked="checked"/>
<input id="second" type="radio" name="radio-set" />
<input id="third" type="radio" name="radio-set" />

<div class="first">Test Text</div>
<div class="second">Test Text 2</div>
<div class="third">Test Text 3</div>

How can I check default checked radio button to add style to its related div on page load?! I added change() to the end of jquery code, but as the default checked attribute is on the button with #first id, it selected the div with .third class.

Upvotes: 0

Views: 500

Answers (2)

RhapX
RhapX

Reputation: 1683

If you're only wanting the code to run once the DOM is ready, you could do something along the lines of:

var selectedInput = $('input[name="radio-set"]:checked').attr('id');
$('div.' + selectedInput).addClass('whatever_style_you_want');

Clearly addClass could be changed to reflect css attributes instead.

Upvotes: -1

glyuck
glyuck

Reputation: 3397

I usually do this by calling .trigger('change') on elements:

$('input[type=radio][name=radio-set]').change(function() {
    // lots of code here
}).trigger('change');

Don't forget to call your function after DOM is ready.

EDIT: sorry, I didn't read your question careful. In your case you should trigger change only on checked radio: .filter(':checked').trigger('change');

Upvotes: 2

Related Questions