jquery 在 while 循环中获取 select2 的数据属性 php
jquery get data attributes of select2 inside while loop php
我一直在查看与 select2 数据属性相关的类似问题,但找不到我要找的内容。我一直在花时间做这件事。
基本上我在 while 循环中有一个 select2 下拉列表,它从 sql 数据库中获取值。 I need to add an additional data attribute and when an option is selected, I need to display the selected data attributed in the input field.我的代码如下
<select class="select2-dropdown form-control" tabindex="-1" id="user" name="user">
<option value="">Select User</option>
<?php
$fetchuser = mysqli_query($link,"SELECT * FROM user ORDER BY name ASC") or die(mysql_error());
while($row=mysqli_fetch_assoc($fetchuser))
{
$id = $row["id"];
$name = $row["name"];
$status = $row["status"];
?>
<option value="<?php echo $id; ?>" data-status="<?php echo $status; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input id="status" />
我的 JS:
<script type=text/javascript>
$('#user').on('select2:selecting', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
</script>
我只得到随机状态(不对应于选定),并且在更改选择时不会显示某些选项状态。
谁能指出我哪里出错了。
提前致谢。
你的代码对我来说太奇怪了。
试试这个:
$('select').on('change', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
我认为它会改变您需要使用的功能
$('#user').on('change', function() {
var status= $(this).find(":selected").data("status");
$('#status').val(status);
});
我一直在查看与 select2 数据属性相关的类似问题,但找不到我要找的内容。我一直在花时间做这件事。
基本上我在 while 循环中有一个 select2 下拉列表,它从 sql 数据库中获取值。 I need to add an additional data attribute and when an option is selected, I need to display the selected data attributed in the input field.我的代码如下
<select class="select2-dropdown form-control" tabindex="-1" id="user" name="user">
<option value="">Select User</option>
<?php
$fetchuser = mysqli_query($link,"SELECT * FROM user ORDER BY name ASC") or die(mysql_error());
while($row=mysqli_fetch_assoc($fetchuser))
{
$id = $row["id"];
$name = $row["name"];
$status = $row["status"];
?>
<option value="<?php echo $id; ?>" data-status="<?php echo $status; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input id="status" />
我的 JS:
<script type=text/javascript>
$('#user').on('select2:selecting', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
</script>
我只得到随机状态(不对应于选定),并且在更改选择时不会显示某些选项状态。
谁能指出我哪里出错了。
提前致谢。
你的代码对我来说太奇怪了。 试试这个:
$('select').on('change', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
我认为它会改变您需要使用的功能
$('#user').on('change', function() {
var status= $(this).find(":selected").data("status");
$('#status').val(status);
});