javascript - Using .click instead of onclick and getting a variable value -


i have seen inline/html events onclick, mouseover etc being used less , less , advised register events using javascript.

i have html like:

<ul id="supported-locations">     <li onclick="setlocationid(32);">mexico</li>     <li onclick="setlocationid(35);">mongolia</li> </ul> 

which works fine want without "onclick" in html still able retrieve id number.

the <li> elements retrieved via ajax while user types input box queries database , retrieve data without loading page.

when user clicks on 1 of countries run setlocationid function sets hidden html form element id of selected country can use once form submitted.

how register event listener these <li>'s when countries , id's different , changing depending on user types box?

use data attribute hold number. on onclick event, read attribute on element clicked.

html:

<ul id="supported-locations">     <li data-code="32">mexico</li>     <li data-code="35">mongolia</li> </ul> 

javascript:

$("#supported-locations").on("click", "li", function() {         var li = $(this);     console.log(li.data("code")); }); 

example:

jsfiddle


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -