I have text boxes and drop downs pairs whose id is generated dynamically. I'm trying to set the css rule (class) on the text box based on a selection in the drop down. I have a the index on the drop down which is what is used to derive the id of the dropdown dynamically. How do I set the CSS rule on the text boxes. If I try to set the class using JavaScript, the change doesn't reflect till I refresh the page.
I'm open to use plain javascript or jquery or a mix of both.
Add a class to your select so you can select them with jQuery easier.
<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. 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;
<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; //wrap the code inside in document.ready.function
$("select").change(function () {
var color = $("#selectoptions").val();
$("#mytext").css("background",color);
});
CSS;
#mytext{
background:red;
}
Here is a Working Live Demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.