Choose one "> 如果只有一个选项,我有这-6ren">
gpt4 book ai didi

php - 选择仅适用于第一个下拉列表的选项

转载 作者:行者123 更新时间:2023-12-01 04:02:09 26 4
gpt4 key购买 nike

所以我有两个下拉菜单:

<select id="list1" name="worker" class="form-control select2" style="width: 100%;">
<option selected="selected">Choose one</option>
<?php foreach($names as $name) { ?>
<option value="<?php echo $name['id'] ?>"><?php echo $name['name'] ?></option>
<?php } ?>
</select>

<select id="list2" name="vehicle" class="form-control select2" style="width: 100%;">
<option selected="selected">Choose one</option>
<?php foreach($cars as $car) { ?>
<option value="<?php echo $car['id'] ?>"><?php echo $car['name'] ?></option>
<?php } ?>
</select>

如果只有一个选项,我有这个 jquery 用于选择第一个选项:

var length1 = $('#list1> option').length;

if (length1 < 3) {
$('select>option:eq(1)').prop('selected', true);
}

var length2 = $('#list2 > option').length;

if (length2 < 3) {
$('select>option:eq(1)').prop('selected', true);
}

即使我只为第二个添加脚本,它也只适用于第一个。

最佳答案

您可以尝试使用以下代码吗:

var length1= $('#list1> option').length;

if(length1< 3) {
$('select#list1>option:eq(1)').prop('selected', true);
}

var length2= $('#list2 > option').length;

if(length2 < 3) {
$('select#list2>option:eq(1)').prop('selected', true);
}

我仍然不太相信您在上面添加的 if 条件。我会推荐下面的代码

var length1= $('#list1> option').length;

if(length1 > 1) {
$('select#list1>option:eq(1)').prop('selected', true);
}

var length2= $('#list2 > option').length;

if(length2 > 1) {
$('select#list2>option:eq(1)').prop('selected', true);
}

在上面的代码中,我们检查是否获得了超过 1 个选项;如果是,那么我们将选择第二个选项,即选择一个选项旁边的选项。

关于php - 选择仅适用于第一个下拉列表的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38892682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com