-1

Hello, I am trying to get my javascript to recognise a folder on each page. Depending on the folder name, I would like to Add that folder name to my innerHTML with if else statements. I'm having trouble getting it to to function with an if else, else if, else statement.

Here is the HTML snippet:

<div id="countryVal"></div>

And the javascript:

var outputData = document.getElementById('clothingVal');

if (window.location.search.search(/Men/)) {
document.getElementById('clothingVal');
outputData.innerHTML = outputData.innerHTML + ': ' + 'Australia';
}

else if (window.location.search.search(/Women/)) {
document.getElementById('clothingVal');
outputData.innerHTML = outputData.innerHTML + ': ' + 'New Zealand';
}

else {outputData.innerHTML = outputData.innerHTML + ': ' + '';
};

Any suggestions would be very much appreciated.

1 Answers1

0

Well not necessary but a switch could be nicer than if elseif else. I find them a little more manageable, when you may want to put a new filter in in the future. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

But keeping your current code you should clean up the variables to make it more readable. And you should also put this code in an onload or onready statment. And prehaps us indexOf over regex (you'll need to escape back slashes to find them something like /\/Men\// which gets messy) How to check whether a string contains a substring in JavaScript?

This is untested, but should be along the lines of what you're after.

window.onload = function() {
    var outputData = document.getElementById('clothingVal');

    if ( window.location.indexOf("/Men/") != -1 ) {
        outputData.innerHTML = outputData.innerHTML + ': ' + 'Australia';
    } else if ( window.location.indexOf("/Women/") != -1 ) {
        outputData.innerHTML = outputData.innerHTML + ': ' + 'New Zealand';
    } else {
        outputData.innerHTML = outputData.innerHTML + ': ' + '';
    };
}
Community
  • 1
  • 1
Lex
  • 4,749
  • 3
  • 45
  • 66