0

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>

3 Answers 3

1

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());
});
Sign up to request clarification or add additional context in comments.

Comments

0

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'));
});

Comments

0

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.