<script type="text/javascript">
/**
*注意上面要引入jquery.js
*去除空格
*/
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, '');
};
//这里是后台传过来一个默认值
var initcunid = '${pkUser.cunid}';
var isInit = false;
var cunidFrist ="";
var ii ;
iniSelect(initcunid);
function iniSelect(cunid){
if(cunid.trim().length == 0){
console.log("小星星为空!");
return;
}
isInit = true;
sendRequest(cunid);
}
function getCunUsers(){
/* alert($('#cunidId').val());*/
var cunid = $('#cunidId').val();
if(cunid.trim().length==0){
alert('请选择村落!');
return;
}
//这里要注意 防止每次点击都加载
if(cunidFrist.trim()!=cunid){
$('#cunUser').html('');
sendRequest(cunid);
}
}
function sendRequest(cunid){
$.ajax({
type: "GET",
url: "${ctx}/pkuser/pkUser/getUsersByCunid",
data: {cunid:cunid},
dataType: "json",
success: function(data){
var html = '<option value="">请选择</option>';
for(var i=0;i<data.length;i++){
html +='<option value="'+data[i].id+'">'+data[i].name+'</option>';
}
$('#cunUser').append(html);
cunidFrist = cunid;
if(isInit){
selectOption();
}
}
});
}
function selectOption(){
$('#cunUser').find("option[value='${pkUser.hzid}']").attr("selected",true);
}
function bianhua(value){
$('#hzid').val(value);
}
</script>
<!--下面是所需的获取数据的关键值-->
<input id="cunidId" name="cunidId" readonly="readonly" type="text" value="这是其实是个id值,村的id" data-msg-required="" class="form-control " style="">
<!--下面是html中的select-->
<input type="hidden" name="hzid" id="hzid" value="">
<select id="cunUser" class="form-control" onclick="getCunUsers()" onchange="bianhua(this.options[this.options.selectedIndex].value)">
</select>
js动态生成select,并初始化后台原有数据
最新推荐文章于 2023-07-10 10:23:57 发布
本文介绍如何使用JavaScript动态生成HTML Select元素,并填充从后台获取的初始数据。通过示例代码,展示如何有效地实现这一功能,使得网页交互更加灵活。
143

被折叠的 条评论
为什么被折叠?



