Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});
like image 500
Rick Bross Avatar asked Apr 16 '13 02:04

Rick Bross


People also ask

Is Datalist tag in HTML5?

The datalist tag is introduced in HTML5. The <datalist> tag should be used with an <input< element that contains a "list" attribute. The value of "list" attribute is linked with the datalist id.

What can you achieve with HTML Datalist tag?

The <datalist> tag is used to provide autocomplete feature in the HTML files. It can be used with an input tag so that users can easily fill the data in the forms using select the data.

Can we style Datalist in HTML?

HTML5 <datalist> elements cannot be styled.


1 Answers

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.

like image 123
likeitlikeit Avatar answered Sep 20 '22 13:09

likeitlikeit