在我的创建表单中,我有两个输入字段。一个是隐藏的,另一个是文本字段。
@Html.HiddenFor(model => model.StateId)
<div class="form-group">
@Html.Label("State", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Editor("StateName", new { htmlAttributes = new { @id="StateName", @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
</div>
</div>
在我的文本字段中,我使用预输入来允许用户选择与他们在文本框中键入的内容相匹配的选项。我的脚本适用于用户实际上选择了一个选项的情况。但如果用户只是输入整个单词,它就不起作用。文本字段适用于美国境内的州。因此,如果用户输入 t
.. 那么包含该字母的状态将出现供用户选择,一旦用户选择了他们想要的状态,该状态的 id
状态将绑定(bind)到隐藏的输入字段。
但是为了我自己的缘故,我知道,如果我要输入 Texas
.. 对我来说直接输入单词会更快,而不是将我的手从键盘上移开并选择选项.但是,如果我这样做......并且不选择该选项...... id
值未绑定(bind)到隐藏的输入字段。
如果用户不从自动完成中选择,我如何仍然绑定(bind)用户想要的状态的 id
?
这是我的脚本:
<script>
$(document).ready(function () {
/* For Auto Complete */
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('state'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/statesapi?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#StateName').typeahead({
highlight: true
},
{
name: 'states',
display: 'state',
source: states,
limit: 10
}).bind('typeahead:select',
function(ev, suggestion) {
$("#StateId").val(suggestion.id);
});
/* ************************** */
});
</script>
最佳答案
由于您总是期望基于输入的 ID,因此您最好自动选择第一个建议。
<script>
$(document).ready(function () {
/* For Auto Complete */
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('state'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/statesapi?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#StateName').typeahead({
highlight: true
},
{
name: 'states',
display: 'state',
source: states,
limit: 10
}).bind('typeahead:select',
function(ev, suggestion) {
$("#StateId").val(suggestion.id);
}).bind("change", function(e) {
var first_suggestion = $(this).parent().find(".tt-suggestion:first-child")
if(first_suggestion.length!=0)
first_suggestion.trigger('click');
//else
// handle invalid input here
});
/* ************************** */
});
</script>
如果没有显示建议,也无法获取输入的 ID,因此您可以重置输入或显示警告...
关于javascript - 通过 Typeahead 将 Id 值绑定(bind)到隐藏的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45844786/