我正在使用jquery auto complete在用户输入任何字符时显示国家/地区名称。 当用户点击按钮然后我想知道如何将国家代码发送到服务器端操作而不是国家名称。
这只是jquery自动完成的一个示例。
<input type="text" class="form-control" id="plugins" name="plugins" />
var myData =[
{"name": "Afghanistan", "code": "AF"},
{"name": "Aland Islands", "code": "AL"},
{"name": "Bahamas", "code": "BM"},
{"name": "Bahrain", "code": "BH"},
{"name": "Cambodia", "code": "CM"},
{"name": "Cameroon", "code": "CN"},
{"name": "Zambia", "code": "ZA"},
{"name": "Zimbabwe", "code": "ZB"}
];
$(function() {
$("#plugins").autocomplete({
source: function(req, resp) {
var results = [];
$.each(myData, function(k, v) {
// Make a pass for names
if (v.name.toLowerCase().indexOf(req.term.toLowerCase()) == 0) {
results.push(v.name)
return;
}
});
resp(results);
},
select: function( event , ui ) {
alert( "You selected: " + ui.item.label+' values '+ ui.item.value );
return false
}
});
});
我知道json中没有国家代码。我将在json写下后来的国家代码。告诉我将国家代码发送到行动的方式。
现在问题已修复。 jsfiddle的工作版本是https://jsfiddle.net/urtkxo46/8/
答案 0 :(得分:0)
尝试这样的事情:
$( function() {
var projects = [
{
value: "1",
label: "jQuery"
},
{
value: "2",
label: "jQuery UI"
},
{
value: "3",
label: "Sizzle JS"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id"> <!-- change it to hidden and get its value -->
答案 1 :(得分:0)
jquery autocomplete可以使用带有标签值键的对象。只需将名称设置为标签,将国家/地区代码设置为值
即可
var myData =[
{"name": "Uganda", "code": "UG"},
{"name": "Kenya", "code": "KY"},
{"name": "Tanzania", "code": "TZ"},
];
$(function() {
$("#plugins").autocomplete({
source: function(req, resp) {
var results = [];
$.each(myData, function(k, v) {
// Make a pass for names
if (v.name.toLowerCase().indexOf(req.term.toLowerCase()) == 0) {
results.push({"label": v.name, "value": v.code})
return;
}
});
resp(results);
},
select: function( event, ui ) {
alert(ui.item.label) //when selected the label shows in alert
}
});
});
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" class="form-control" id="plugins" name="plugins" />