我想在onchange
事件和页面加载中调用一个函数来编辑页面。这是我的select标签,这里我在onchange
事件上调用了一个函数,但是我想在页面加载时调用这个函数。
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-edit fa-lg" aria-hidden="true"></i></span>
<?php foreach ($get_institute as $get_institutes) { ?>
<select name="state_name" class="form-control" id="state_id" onchange="change_state(this.options[this.selectedIndex].value);
stateName();
document.getElementById('selected_text').value = this.options[this.selectedIndex].text" style="width: 100%;">
<?php foreach ($get_state as $get_states) { ?>
<?php if ($get_states['id'] == $get_institutes['state_id']) { ?>
<option value="<?php echo $get_states['id']; ?>" selected><?php echo $get_states['name']; ?></option>
<?php } else { ?>
<option value="<?php echo $get_states['id']; ?>"><?php echo $get_states['name']; ?></option>
<?php } ?>
<?php } ?>
</select>
<input type="hidden" name="state" id="state">
</div>
这是我的功能
<script>
function change_state(state_id) {
if (state_id == "Select") {
$("#city_id").html("<option>Select</option>");
$("#city_id").trigger("chosen:updated");
$("#city_id").trigger("liszt:updated");
} else {
loadData(state_id);
}
}
function loadData(state_id) {
var dataString = 'state_id=' + state_id;
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?
>admin/select_city_by_state_id",
data: dataString,
cache: false,
success: function (result) {
$("#city_id").html("<option>Select</option>");
$("#city_id").append(result);
$("#city_id").trigger("chosen:updated");
$("#city_id").trigger("liszt:updated");
}
});
}
window.onload = change_state;
</script>
<script>
function stateName() {
var label1 = document.getElementById('state_id')
[document.getElementById('state_id').selectedIndex].innerHTML;
$('#state').val(label1);
}
window.onload = stateName;
</script>
这里我使用window.onload
,但我的功能无法加载。
答案 0 :(得分:0)
删除此
window.onload = change_state; //remove this
将其用作
<script>
$(document).ready(function(){
change_state();
});
</script>
答案 1 :(得分:0)
首先,您必须从选择下拉列表中删除onchange事件。
<select name="state_name" class="form-control" id="state_id">
然后添加该函数并调用onload以及onchange:
function change_state() {
var sel = document.getElementById("state_id");
var text= sel.options[sel.selectedIndex].text;
if (state_id == "Select") {
$("#city_id").html("<option>Select</option>");
$("#city_id").trigger("chosen:updated");
$("#city_id").trigger("liszt:updated");
} else {
loadData(state_id);
}
}
document.addEventListener("DOMContentLoaded", function() {
change_state();
});
$('#state_id').change(function() {
change_state();
});