javascript - Event listener code won't execute function as expected -
i trying write small javascript function takes data opensignal , displays in html table.
this worked fine until point tried make user friendly adding in html form accept postcodes input. tried avoid using php client won't have installed.
i adding event listener submit button detect when form data has been submitted. taking , validating string contains valid postcode(s). if they're invalid program spits out alert says "sorry seem have entered incorrect postcode.".
if not taking postcodes , passing them function processpostcodesonserver(). thing doesn't work inside event listener. when pass postcodes in manually using javascript arrays , call function outside of event listener works fine. when put in event listener doesn't work. have checked inputs function correct , have stepped through whole program numerous times , cannot find out causing problem. seems me case of javascripts random behaviour.
can help?? html , javascript files (i using jquery have link latest version if want run this).
<!doctype html> <html> <head> <title>mobile signals</title> <script src="jquery-1.11.3.min.js"></script> <script src="networkstats.js"></script> </head> <body> <form id="postcodeform"> enter postcodes separated commas<br> <input type="text" id="postcodes" name="postcodes"> </br></br> <input type="submit" value="submit" id="submitbutton"> </form> <div id="thediv"> </div> <div id ="seconddiv"> </div> <table id="thetable" border="1"> </table>
and javascript
$( document ).ready(function() { document.getelementbyid('submitbutton').addeventlistener('click', function() { var input = $('#postcodeform').serializearray(); var postcodestring = input[0]["value"]; var output = postcodestring.split(","); var postcodestring = ""; // check each postcode see if there false postcodes (var postcode in output) { var newpostcode = checkpostcode(output[postcode]); if (newpostcode) { postcodestring += " true "; } else { postcodestring += " false "; } } if (postcodestring.indexof("false") >= 0) { // string contains false output error message window.alert("sorry seem have entered incorrect postcode.") } else { // postcodes correct, proceed perform operations on them processpostcodesonserver(output); } }, false); function processpostcodesonserver(output) { var apikey = "c590c63f5b3818271a87a3e89fa215ae"; var distance = 10; var tablenumber = 0; //var output = ["wr141ne"]; (var postcode in output) { strippedpostcode = output[postcode].replace(/ /g,''); getlatandlong(strippedpostcode); } function googlecallback(latitude, longitude, postcode) { contactserver(latitude, longitude, postcode); } /* function contact google , convert postcode lat long */ function getlatandlong(postcode) { var latitude; var longitude; var googlexmlhttp = new xmlhttprequest(); var googleurl = "http://maps.googleapis.com/maps/api/geocode/json?address="+ postcode + "&sensor=false"; googlexmlhttp.onreadystatechange = function() { if (googlexmlhttp.readystate == 4 && googlexmlhttp.status == 200) { var latlong = json.parse(googlexmlhttp.responsetext); latitude = latlong.results[0].geometry.location.lat; longitude = latlong.results[0].geometry.location.lng; googlecallback(latitude, longitude, postcode); } } googlexmlhttp.open("get", googleurl, true); googlexmlhttp.send(); } function contactserver(latitude, longitude, postcode) { var xmlhttp = new xmlhttprequest(); var networkstatsurl = "http://api.opensignal.com/v2/networkstats.json?lat="+latitude+"&lng="+longitude+"&distance=" + distance + "&apikey=" + apikey; /* functions contact server , read json response networkstats */ xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { var myarr = json.parse(xmlhttp.responsetext); sorttabledata(myarr, postcode); //displaydata(myarr); } } xmlhttp.open("get", networkstatsurl, true); xmlhttp.send(); var functioncount = -1; function sorttabledata(arr, postcode) { tablenumber++; $("body").append("</br>" + postcode + "</br>"); thetable = "<table id='table"+ tablenumber + "' border='1'> </table>" $("body").append(thetable); var column1 = new array(); var column2 = new array(); var column3 = new array(); var column4 = new array(); var column5 = new array(); var column6 = new array(); var column7 = new array(); //var output = '<table border="1">'; //var output = ""; (var obj in arr) { // find networks if ((typeof arr[obj] === 'object') && (obj == "networkrank")) { var networks = new object(); networks = arr[obj]; var allnetworkkeys = object.keys(networks); //console.log(allnetworkkeys); var networksarray = new array(); $.each(networks, function(networkkey, networkvalue){ //do key , value. column1.push(networkkey); if (networkkey.substring(0, 7) == "network") { $.each(networkvalue, function(networktypekey, networktypevalue){ if (networktypekey == "type2g") { column2.push(''); column3.push(networktypekey); (var variable in networktypevalue) { column2.push(variable); column3.push(networktypevalue[variable]); } } else if (networktypekey == "type3g") { column4.push(''); column5.push(networktypekey); (var variable in networktypevalue) { column4.push(variable); column5.push(networktypevalue[variable]); } } else if (networktypekey == "type4g") { column6.push(''); column7.push(networktypekey); (var variable in networktypevalue) { column6.push(variable); column7.push(networktypevalue[variable]); } } }); //console.log(column1); } //console.log(column1, column2, column3, column4); displaytable(column1, column2, column3, column4, column5, column6, column7); column1 = []; column2 = []; column3 = []; column4 = []; column5 = []; column6 = []; column7 = []; }); } } } var counter = 0; function displaytable(column1, column2, column3, column4, column5, column6, column7) { var output = "" //console.log(counter); counter++; var column1length = column1.length; var column2length = column2.length; var column3length = column3.length; var column4length = column4.length; var column5length = column5.length; var column6length = column6.length; var column7length = column7.length; var highestnumber = math.max(column1length, column2length, column3length, column4length, column5length, column6length, column7length); (var i=0; i<highestnumber; i++) { var column1reference = column1[i]; var column2reference = column2[i]; var column3reference = column3[i]; var column4reference = column4[i]; var column5reference = column5[i]; var column6reference = column6[i]; var column7reference = column7[i]; if (column1reference === void 0) { column1reference = " " } if (column2reference === void 0) { column2reference = " " } if (column3reference === void 0) { column3reference = " " } if (column4reference === void 0) { column4reference = " " } if (column5reference === void 0) { column5reference = " " } if (column6reference === void 0) { column6reference = " " } if (column7reference === void 0) { column7reference = " " } output += "<tr>"; output += "<td>" + column1reference + "</td>"; output += "<td>" + column2reference + "</td>"; output += "<td>" + column3reference + "</td>"; output += "<td>" + column4reference + "</td>"; output += "<td>" + column5reference + "</td>"; output += "<td>" + column6reference + "</td>"; output += "<td>" + column7reference + "</td>"; output += "</tr>"; } //output += "</table>"; //var table = document.getelementbyid('thetable'); //console.log(output); //oldoutput = table.innerhtml; //table.innerhtml = oldoutput + output; $("#table" +tablenumber).append(output); console.log(output); } } } });
alright, got working.
table displayed, if submitting form wouldn't reload page.
there 2 ways around this:
change
click
handlersubmit
handler and cancel event!replace
document.getelementbyid('submitbutton').addeventlistener('click', function() { // ... }, false);
by
document.getelementbyid('postcodeform').addeventlistener('submit', function(event) { event.preventdefault(); // ... }, false);
remove form:
that simple removing
<form id="postcodeform">
,</form>
html code, since use$('#postcodeform')
in js, you're gonna have changevar input = $('#postcodeform').serializearray(); var postcodestring = input[0]["value"]; var output = postcodestring.split(",");
into
var output = document.getelementbyid('postcodes').value.split(",");
to make work.
(inliningpostcodestring
not necessary, suggest it, see below.)
if go option, suggest removingname
attribute#postcodes
, because serves no purpose.
but regardless of option choose, should fix </br>
s: it's <br>
in html 5 (and <br/>
in html 4, never </br>
).
(and don't forget in js!)
and googlecallback
function for, if passes arguments function exact same list of parameters? why not use contactserver
directly?
and code inefficient:
var postcodestring = ""; // check each postcode see if there false postcodes for(var postcode in output) { var newpostcode = checkpostcode(output[postcode]); if(newpostcode) { postcodestring += " true "; } else { postcodestring += " false "; } } if(postcodestring.indexof("false") >= 0) { // string contains false output error message window.alert("sorry seem have entered incorrect postcode.") } else { // postcodes correct, proceed perform operations on them processpostcodesonserver(output); }
i mean, strings, really? consider:
// check each postcode see if there invalid postcodes for(var postcode in output) { if(checkpostcode(output[postcode]) === false) { // current postcode invalid output error message , return window.alert("sorry seem have entered incorrect postcode."); return; } // @ point, postcodes valid, proceed perform operations on them processpostcodesonserver(output);
also, use lot of variables once, resulting in quite overhead.
example, this:
var column1length = column1.length; var column2length = column2.length; var column3length = column3.length; var column4length = column4.length; var column5length = column5.length; var column6length = column6.length; var column7length = column7.length; var highestnumber = math.max(column1length, column2length, column3length, column4length, column5length, column6length, column7length);
which shortened this:
var highestnumber = math.max(column1.length, column2.length, column3.length, column4.length, column5.length, column6.length, column7.length);
sure makes line little longer, 7 additional characters can save 7 entire lines!
or, displaytable
function shortened this:
function displaytable() { var output = ''; var highestnumber = math.max(arguments[0].length, arguments[1].length, arguments[2].length, arguments[3].length, arguments[4].length, arguments[5].length, arguments[6].length); for(var = 0; < highestnumber; i++) { output += '<tr>'; for(var j = 0; j < 7; j++) { output += '<td>' + arguments[j][i] + '</td>'; } output += '</tr>'; } $('#table' + tablenumber).append(output); }
then, have lot of {1}
in regex - why? [0-9]{1}
equal [0-9]
(or \d
, careful escape \
if using in strings).
and finally, suggest run code through jshint or similar rid of inconsistencies (be careful jslint though, 1 has aggressive , unreasonable conventions).
Comments
Post a Comment