Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

html - jQuery event when HTML5 Datalist option is clicked

What I have now:

So i have this HTML5 Datalist with a bunch of options in it, and I have 2 events firing. One when the user types out something that matches something the array of names that is populating the options such as "Rick Bross" or "Jack Johnson" (keyup). Another event that fires when a user starts typing the name, it pops up, the user arrows down, and hits "enter" (change).

The problem:

I need an event to fire when the user clicks one of the drop down options, BEFORE he types the full name out, and before the object is blurred. If a user clicks one right now before the name is completely typed out, the 2 events only fire the function once the input is blurred.

The Markup:

<datalist id="potentials">
    <option value="Rick Bross">  
    <option value="Jack Johnson">  
    <option value="Rick Bross">  
    <option value="Rick Bross">   
</datalist>

Javascript events and functions:

window.checkModelData = function(ele)
{
    var name = $(ele).val().replace(" ", "");
    var mod = potentialModels[name];
    if(mod) {
        loadModelData(name);
    }
}

function loadModelData(name) {
    var mod = potentialModels[name];
    $("#address").val(potentialModels[name].address);
    $("#city").val(potentialModels[name].city);
    $("#state").val(potentialModels[name].state);
    $("#email").val(potentialModels[name].email);
    $("#phone").val(potentialModels[name].phone);
    $("#zip").val(potentialModels[name].zip);
}

$("#name").keyup(function(){

    window.checkModelData(this);

});
$("#name").change(function(){

    window.checkModelData(this);
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the input event instead of the other events. It's actually designed to cover what you want:

$("#name").bind('input', function () {
    window.checkModelData(this);
});

I made a jsfiddle for you to try it out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...