NickyMan NickyMan - 3 months ago 24
Javascript Question

unable to get span value

I'm new to Javascript and Jquery, just started learning, I copied code from other website and do some slight changes, I'm trying to update the timer when clicking on icons, but I received this error:-

Uncaught TypeError: Cannot read property 'split' of undefined


After finding, I see that variable myTime is undefined. It did not get span value. Here is my code:-

function updateTimer(expiryid) {
var myTime = $(expiryid+ ' span').html();
console.log(myTime);
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);

var dt2 = new Date(dt.valueOf() + 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");

expiryid.html(ts[1]+":"+ts[2]);
}


function initialize() {
// Some un-related code up here

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
//console.log('expire_'+i);
updateTimer('#expire_'+i);
}
})(marker, i));

}

</script>

<span id="expire_4">06:51</span>

Answer

You html is <span id="expire_4">06:51</span> yet you are trying to query var myTime = $(expiryid+ ' span').html(); where expiryid = '#expire_'+i. The issue is your query doesn't match your code. Your query suggests that you expect there to be an element with id expire_<number> that has a child span. What you have is a span with id expire_<number>. Update the query to get the span element as $(expiryid) and you should be good to go.

Edit I also noticed you are trying to update the html of a variable. Update the entire function to:

function updateTimer(expiryid) {
            var myTimeEl = $(expiryid); /* create jquery object*/
            var myTime = myTimeEl.html(); /*get the date string*/
            console.log(myTime);
            var ss = myTime.split(":");
            var dt = new Date();
            dt.setHours(0);
            dt.setMinutes(ss[0]);
            dt.setSeconds(ss[1]);

            var dt2 = new Date(dt.valueOf() + 1000);
            var temp = dt2.toTimeString().split(" ");
            var ts = temp[0].split(":");

            myTimeEl.html(ts[1]+":"+ts[2]); /*add new string to element using jquery objct*/
        }
Comments