matt_50 matt_50 - 10 days ago 6
Javascript Question

Javascript - how to avoid long/ugly if/else statements?

I'm learning Javascript (mainly using JQuery) and was wondering if somebody could help me.

I've written an if/else statement that checks to see if a particular string appears in the URL, then posts a forms content to a particular php script depending on the string.

Q: The code I'm using works, BUT feels clumsy and unnecessarily long! - I figure there MUST be a simpler way to write this!? I've had a look around but most answers just seem to provide code without anything to help me understand how it was done..

What I'm trying to achieve is:


  1. A user completes one of 4 signup forms (prereg1.html, prereg2.html, prereg3.html, prereg4.html)

  2. Depending on the URL, the if/else statement sends the form data to a corresponding PHP script (add_prereg1.php, add_prereg2.php etc.) which adds the data to an email list database (hosted by campaign monitor)



note: My php knowledge is pretty poor too - because the campaign monitor lists each have unique IDs, the only way I can get the php to post the form data in the right list is to have 4 separate 'prereg.php' scripts. I'm sure there is a way to get the php script to figure out which list to post to based on the variables passed by the javasscript but this is a bit beyond me at this stage! Any pointers welcome..

Anyhow here is the if/else statement:

if (document.location.href.indexOf('prereg1') > -1) {
$.ajax({
type: "POST",
url: "bin/add_prereg1.php",
data: 'name=' + name + '&email=' + email
});
}

else {
if (document.location.href.indexOf('prereg2') > -1) {
$.ajax({
type: "POST",
url: "bin/add_prereg2.php",
data: 'name=' + name + '&email=' + email
});
}

else {
if (document.location.href.indexOf('prereg3') > -1) {
$.ajax({
type: "POST",
url: "bin/add_prereg3.php",
data: 'name=' + name + '&email=' + email
});
}

else {
if (document.location.href.indexOf('prereg4') > -1) {
$.ajax({
type: "POST",
url: "bin/add_prereg4.php",
data: 'name=' + name + '&email=' + email
});
}
}
}
}


Thanks for any help.

Answer

Consider this:

var match = window.location.href.match( /prereg(\d)/ );

if ( match ) {
    $.ajax({
        type: 'POST',
        url: 'bin/add_prereg' + match[1] + '.php',
        data: 'name=' + name + '&email=' + email
    });
}

Live demo: http://jsfiddle.net/4MWDm/

You simply search the string for the sequence "prereg" followed by a digit. The parens capture the digit, so you can access it with [1].


Btw use window.location instead of document.location.

document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead.

Source: https://developer.mozilla.org/en/DOM/document.location