Dave Dave - 2 months ago 10
jQuery Question

accessing data from websql

Good Morning, I have a script that retrieves data from a WebSQL db, it works fine.

$(document).ready(function(e) {
var v= location.search.replace("?init=", "");
document.getElementById('key').innerHTML=v;

var db = openDatabase('contacts', '1.0', 'contacts database', 5 * 1024 * 1024); var x = v + "%";
db.transaction(function(tx){
tx.executeSql('SELECT * FROM names WHERE lname LIKE "' + x +'"', [], function (tx, results){
var len = results.rows.length, i;
if(len > 1 ){ // if len is greater than 1
for (i = 0; i < len; i++) {
$('#nameList').append("<li data-url='autolkp.html?id='" + results.rows.item(i).lname + "' class='n' id='"+results.rows.item(i).lname+"'>" + results.rows.item(i).lname + "</li>");
}
} // closes if len is greater than 1
else {
$("#fName").val(results.rows.item(0).fname);
$("#lName").val(results.rows.item(0).lname);
$("#adx").val(results.rows.item(0).adx);
$("#city").val(results.rows.item(0).city);
$("#state").val(results.rows.item(0).st);
$("#zip").val(results.rows.item(0).zip);
$("#phone1").val(results.rows.item(0).phone1);
$("#phone2").val(results.rows.item(0).phone2);
$("#email").val(results.rows.item(0).email);
} }); }); });


this script takes the results from the query and creates a list with the last names.

I am trying to access the data-url from the li with this script

$(document).ready(function(){
$('li').click(function(){
a = $(this).attr('data-url');
alert(a);
}); });


it isn't working. when you do a view page source - none of the data from the executeSql is visible, but when you go into console it is. Is this a timing issue? How can I get around it?

Thx.

Answer

You're setting the <li> click listener before it renders the results. You just need to change the click listener to this:

$(document).ready(function () {
  $('#nameList').on('click', 'li', function() {
    // DO SOMETHING
  });
});