我正在尝试编写一个在Materialize.css自动完成选项未时选择执行的函数。这可能吗?基本上我想根据名称字段中用户选择的自动完成选项自动为电子邮件字段添加值,这样可以正常工作。但是当用户键入自定义名称时,我还希望该电子邮件值消失,到目前为止,如果没有某种“清除”按钮,我无法使其工作。我试过写这样的if / else语句:
$('input.autocomplete').autocomplete({
data: {
//Data options
},
limit: 20,
onAutocomplete: function(val) {
if ( $("#personname").val() == "last name, first" ) {
$("#personemail").val("email@business.com");
}
else {
$("#personemail").val("");
}
},
minLength: 1,
});
但这似乎不起作用,因为(我认为)只有在执行了自动完成功能后才能运行此功能?
答案 0 :(得分:2)
在您的特定情况下,不需要onAutocomplete
功能。我处理它的方法是在$("#personemail")
字段上创建一个监听器,该监听器将检查自动完成中是否存在值。
我创造了一些东西(我认为)解决了你遇到的问题,请在JSfiddle上查看:
$(function() {
$('#personname').val('last name, first'); // proof of concept, assuming a user would input this
Materialize.updateTextFields(); // remove it and you can see the visual bug
$('.autocomplete').autocomplete({
data: {
"apple": null,
"banana": null,
"yellow": null,
"purple": null,
"green": null,
"blue": null
},
limit: 20,
onAutocomplete: function(val) {
if ($('#personname').val() == 'last name, first') {
$('#personemail').val('email@business.com');
Materialize.updateTextFields();
}
},
minLength: 1,
});
$('#personname').change(function() {
$("#personemail").val('');
});
});

@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: local('Material Icons'), local('MaterialIcons-Regular'), url(https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-webkit-font-feature-settings: 'liga';
-webkit-font-smoothing: antialiased;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css" rel="stylesheet" />
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">add</i>
<input type="text" id="personname">
<label for="personname">Name</label>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Autocomplete</label>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">personpin</i>
<input type="text" id="personemail">
<label for="personemail">Email</label>
</div>
</div>
</div>
</div>
&#13;