简体   繁体   English

如何使用Javascript或jQuery更改select元素的每个选项的内容

[英]How to change the content for each option of select element with Javascript or jQuery

My task here is to change the content in the table whenever the select's options change. 我的任务是每当select的选项改变时改变表中的内容。

The code below is my solution but I don't think that is good at all. 下面的代码是我的解决方案,但我认为这根本不是很好。 What if when the options have more than 3 options... this might lead me to modify lots of in the if else condition. 如果选项有超过3个选项怎么办...这可能会导致我修改if else条件中的大量if else Thus, if you have others solution, please let me know that. 因此,如果您有其他解决方案,请告诉我。

Might I set id="approve_2" as show default with my edited JSFIDDLE? 我可以将id="approve_2"设置为我编辑的JSFIDDLE的默认设置吗?

Demo 演示

HTML: HTML:

<table>
<tr>
    <td>
        <select id="select_vehicle">
            <option value="company_vehicle">Company Vehicle</option>
            <option value="hiring_vehicle">Hiring Vehicle</option>
            <option value="taxi">Taxi</option>
        </select>
    </td>
</tr>
<tr id="company_vehicle">
    <td>Company Vehicle</td>
</tr>
<tr id="hiring_vehicle">
    <td>Hiring Vehicle</td>
</tr>
<tr id="taxi">
    <td>Taxi</td>
</tr>
</table>

Javascript: 使用Javascript:

var select_vehicle = $("#select_vehicle");
// Set selected item
var set_selected_item = $(select_vehicle).val("company_vehicle");
// Hide options "Hiring Vehicle" & "Taxi"
var company_vehicle = $("#company_vehicle"); // Get id "Company Vehicle"
var hiring_vehicle = $("#hiring_vehicle"); // Get id "Hiring Vehicle"
hiring_vehicle.hide();
var taxi = $("#taxi"); // Get id "Taxi"
taxi.hide();


$(select_vehicle).on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if (valueSelected == "company_vehicle") {
    company_vehicle.show();
    hiring_vehicle.hide();
    taxi.hide();
} else if (valueSelected == "hiring_vehicle") {
    company_vehicle.hide();
    hiring_vehicle.show();
    taxi.hide();
} else {
    company_vehicle.hide();
    hiring_vehicle.hide();
    taxi.show();
}
});

JSFIDDLE: http://jsfiddle.net/huydq91/7us66/3/ JSFIDDLE: http //jsfiddle.net/huydq91/7us66/3/

You can shorten your code without repetition like this: 您可以缩短代码而不重复这样的:

$('table tr:gt(0)').hide();
$('#select_vehicle').change(function() {
    var val = $(this).val();
    $('#'+val).show().siblings('tr').not(':first').hide();    
}).change();

Updated Fiddle 更新小提琴

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

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