jflay
jflay

Reputation: 514

Creating Conditional Statement Based On Page URL

I am using Mapquests gps lookup API and Wordpress, so am applying the same map.js functions to populate longitude, latitude and address for fields existing on completely different pages of the same site. For example, this is what I have so far (latitude example only) and can ONLY get the first statement to work, while others don't on the other pages, that is, populating field with the value.

Better yet, is there a better way, besides GetElementById to fill these form ids that exist on different pages? It fails if the value is null, since it looks for the ID that isn't on the page...

Found this example: Javascript match part of url, if statement based on result

JS

var str = "http://wordpressite.com/soco-app/forms/lights-out/report-vegetation-growth-web/report-vegetation-growth-iphone/"
if (str.indexOf("http://wordpressite.com/soco-app/forms/lights-out") === 0) {
document.getElementById("input_1_11").value = latitude;
} else if (str.indexOf("http://wordpressite.com/soco-app/forms/report-vegetation-growth-web") === 0) {
document.getElementById("input_2_6").value = latitude;
} else if (str.indexOf("http://wordpressite.com/soco-app/forms/report-vegetation-growth-iphone") === 0) {
document.getElementById("input_3_6").value = latitude;
}

HTML for Page 1 - lights-out

<li id='field_1_11' class='gfield     gform_hidden' ><input name='input_11' id='input_1_11' type='hidden' class='gform_hidden' value='' /></li><li id='field_1_12' class='gfield     gform_hidden' ><input name='input_12' id='input_1_12' type='hidden' class='gform_hidden' value='' /></li><li id='field_1_13' class='gfield     gform_hidden' ><input name='input_13' id='input_1_13' type='hidden' class='gform_hidden' value='' /></li>

HTML for Page 2 - report-vegetation-growth-web

<li id='field_2_6' class='gfield     gform_hidden' ><input name='input_6' id='input_2_6' type='hidden' class='gform_hidden' value='' /></li><li id='field_2_7' class='gfield     gform_hidden' ><input name='input_7' id='input_2_7' type='hidden' class='gform_hidden' value='' /></li><li id='field_2_8' class='gfield     gform_hidden' ><input name='input_8' id='input_2_8' type='hidden' class='gform_hidden' value='' /></li>

That's the gist.... I am using gravity forms plugin, but the IDs, once the fields are created, are static unless I delete a field.

Upvotes: 1

Views: 3306

Answers (1)

JayMoretti
JayMoretti

Reputation: 265

you can try:

var str = window.location.pathname; // get the current URL;
var el; // cache element;
if(str.indexOf('lights-out') > -1) {
    el = document.getElementById("input_1_11");
} else if(str.indexOf('growth-web') > -1) {
    el = document.getElementById("input_2_6");
} else if(str.indexOf('growth-iphone') > -1) {
    el = document.getElementById("input_3_6");
}

if(el)
    el.value = latitude;

Upvotes: 2

Related Questions