gpt4 book ai didi

javascript - 未从选择标签中获取所选项目

转载 作者:行者123 更新时间:2023-12-01 03:00:36 25 4
gpt4 key购买 nike

下面给出的是我编写的代码片段,用于获取用户从下拉列表中选择的类代码和部分的值。但我只获取选择的第一个元素,而不是获取选定的元素。

HTML 代码:

<div id="dialog-form" title="Create New Academic Year">
<p class="validateTips">All form fields are required.</p>
<fieldset>

<label for="class_code">Class</label>
<select name="class_code" id="class_code" class="text ui-widget-content ui-corner-all">
<?php
include_once 'config.php';
$sql = "select class_code from list_class";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row['class_code'] ?>"><?php echo $row['class_code'] ?></option>
<?php
}
?>
</select>
<label for="section">Section</label>
<select name="section" id="section" class="text ui-widget-content ui-corner-all" multiple>
<?php
include_once 'config.php';
$sql = "select section_code from list_sections";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row['section_code'] ?>"><?php echo $row['section_code'] ?></option>
<?php
}
?>
</select>
</fieldset>
</div>

JS代码:

var new_dialog = function (type, row) {
var dlg = $("#dialog-form").clone();
type = type || 'Create';
var config = {
autoOpen: true,
height: 300,
width: 350,
modal: true,
buttons: {
"Insert": function () {
//To get the class_code value
alert($('select[name="class_code"]').val());
//To get the section value
alert($('select[name="section"]').val());

},
"Cancel": function () {
dlg.dialog("close");
}
},
close: function () {
dlg.remove();
}
};
dlg.dialog(config);
};
$("#create-user").button().click(new_dialog);

我什至尝试过

alert($('#class_code option:selected')val());

但即使这样也不起作用。有人可以帮我解决我出错的地方吗?提前致谢。

最佳答案

您不必选择所选选项 - 您只需选择选择框本身

alert($('#class_code').val());

就您而言,还有一个问题。您克隆了表单,因此每个选择框在 dom 中存在多次,并且 val() 仅返回第一个选择框的选定值,即列表中的第一个元素。

你必须选择 - 摆脱克隆或尝试这样的事情

alert($('select[name="class_code"]', dlg).val());

将 dlg 添加到上下文中会使 jquery 在克隆元素内进行搜索,这应该可以解决您的问题

关于javascript - 未从选择标签中获取所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46444942/

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