eZa
eZa

Reputation: 3

jQuery addClass using input select

Im a bit of a jQuery novice.

I have 5 options in a drop down menu. I want to add a class in a div depending on which option is selected. This class will then change the layout of the content using CSS.

Here is an example if it helps!

Thanks

<form>

<select>
<option id="1">layout 1</option>
<option id="2">layout 2</option>
<option id="3" selected>layout 3</option>
<option id="4">layout 4</option>
<option id="5">layout 5</option>
</select>

<div class="3">styled content</div>

</form>

Upvotes: 0

Views: 3948

Answers (3)

mnsr
mnsr

Reputation: 12437

You can use the ".attr()" to set the class attribute of the div onchange. You're best to change the option id to value first. then:

$("select").change(function() {
   $("div").attr("class", $(this).val());
});

(EDIT) Change it to:

$("select#np_blog_layout").change(function() {
   $("div#changebox").attr("class", $(this).val());
});

Upvotes: 1

kazinix
kazinix

Reputation: 30113

First off, you don't have to use id to your options. Put the values in value attribute. Put ID to your div and select so you can select them using jQuery.

<form>

<select Id="selectElement">
<option value="1">layout 1</option>
<option value="2">layout 2</option>
<option value="3" selected>layout 3</option>
<option value="4">layout 4</option>
<option value="5">layout 5</option>
</select>

<div id="styledContent" class="3">styled content</div>

</form>

On JS

    //Attach event handler to select element's onchange event
$('#SelectElement').bind("change",changeStyle);

    //The event handler
function changeStyle()
{
       //Set class to selected value
   $('#styledContent').class($('#SelectElement').val());
}

Upvotes: 0

Stoney
Stoney

Reputation: 728

What 'rudeovski ze bear' said, but if you still want to set it to the div's class to the selected elements id, here it is.

$('select').change(function() {
    $('div').attr('class', $(this).attr('id'));
});

Upvotes: 0

Related Questions