这里我使用数据列表我有一个URL,因为我正在传递areaId = 2& areaName = Chennai,现在我必须取值,我想让这个值被选中,我想再次更改areaName所以我改变而不是Chennai,我改变了Karur意味着我最后点击提交按钮意味着我想要采取区域和& AREANAME
$('.options').on('change', function() {
var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
$('#city_id').val(city_id);
console.log(city_id);
});
function myFunction (){
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="POST">
<input list="options" type="name" class="form-control options" style="border-radius:0px;height: 36px;" name="location12" id="location12" placeholder="City" rel='<?php echo $_GET['areaId']?>' value='<?php echo $_GET['areaName']?>'>
<datalist id="options">
<option data-id="1" value="Bangalore"></option>
<option data-id="2" value="Chennai"></option>
<option data-id="3" value="Karur"></option>
</datalist>
<input type="hidden" name="city_id" id="city_id">
<input type="submit" value="submit">
</form>
答案 0 :(得分:0)
你有3个选项,要么使用默认的PHP值来设置文本输入值,要使用JS动态设置加载/准备好的city_id
值,请相反并设置datalist对应的选项并添加{在PHP中{1}}并在加载时更新文本输入,或者最后在PHP中设置它们。
这是PHP最简单的情况:设置文本输入值并更新selected="selected"
。对于第二个解决方案,还有一些代码,因为您必须测试选项并在好的情况下手动添加city_id
。我个人更喜欢第二种,因为您的PHP值实际上将根据选项进行验证,以便在PHP值错误且与任何选项值不对应时不会选择任何内容。
selected="selected"
&#13;
$('.options').on('change', function() {
var city_id = $('#options option[value="' + $('#location12').val() + '"]').data('id');
$('#city_id').val(city_id);
console.log(city_id);
});
//setting one of the element value based on the other's default value:
$(document).ready(function(){
//use this to set text input based on default selected option
//$('#location12').val($('#options option:selected').val());
//console.log('text input is now: ' + $('#location12').val());
//or this for the other way round
$('#city_id').val($('#options option[value="' + $('#location12').val() + '"]').data('id'));
console.log('city_id is now: ' + $('#city_id').val());
});
function myFunction (){
}
&#13;