简体   繁体   English

根据下拉列表中的选择设置CSS规则

[英]Setting a CSS rule based on a selection in a drop down

I have text boxes and drop downs pairs whose id is generated dynamically. 我有动态生成id的文本框和下拉对。 I'm trying to set the css rule (class) on the text box based on a selection in the drop down. 我正在尝试根据下拉列表中的选择在文本框中设置css规则(类)。 I have a the index on the drop down which is what is used to derive the id of the dropdown dynamically. 我有一个下拉列表的索引,用于动态地导出下拉列表的id。 How do I set the CSS rule on the text boxes. 如何在文本框中设置CSS规则。 If I try to set the class using JavaScript, the change doesn't reflect till I refresh the page. 如果我尝试使用JavaScript设置类,则在我刷新页面之前,更改不会反映出来。

I'm open to use plain javascript or jquery or a mix of both. 我愿意使用普通的javascript或jquery或两者兼而有之。

Add a class to your select so you can select them with jQuery easier. 在您的选择中添加一个类,以便您可以更轻松地使用jQuery选择它们。

<div>
    <select id="Generated1234" class="cssRule">
        <option value="class1">Class #1</option>
        <option value="class2">Class #2</option>
    </select>
    <input type="text" name="Generated1234_text"/>
</div>

jQuery code, assuming your input textbox is a sibling of the select. jQuery代码,假设您的输入文本框是select的兄弟。 You may need to change the last line to select the correct textbox. 您可能需要更改最后一行以选择正确的文本框。

$(document).ready(function(){
    $('select.cssRule').change(function(){
        var $this = $(this);
        var className = $this.val();
        $this.siblings('input[type=text]').attr('class', className);
    }
}

You may try something like; 你可以试试像;

HTML; HTML;

<select id="selectoptions" class="cssRule">
        <option class="class1" value="red">red</option>
        <option class="class2" value="blue">blue</option>
    </select>
<input id="mytext" type="text" name="mytext"/>

JavaScript; JavaScript的; //wrap the code inside in document.ready.function //将文件包装在document.ready.function中

$("select").change(function () {
    var color = $("#selectoptions").val();
    $("#mytext").css("background",color);
});

CSS; CSS;

#mytext{
    background:red;
}

Here is a Working Live Demo 这是一个工作现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM