2

I want to insert different url's dynamically after checking a condition

Here's the pseudocode

If div.id = "abc" then
create url <a href="www.zzz.html"'>Cosmetics</a>');
Append url to div

else if div.id = "xyz" then
create url <a href="www.abc.html"'>LEather goods</a>');
Append url to div

else if div.id = "mno" then
create url <a href="www.kkk.html"'>Diapers</a>');
Append url to div

and so on.

How can I write this in JavaScript/jQUery. How to handle the code efficiently if there are 15 such If-Else conditions.

This code is not looking good

if $("#abc) then

 var dynLink = $('<a href=zzz.html"'>Cosmetics</a>');
    $("#abc").append(dynLink);

else if $("#xyz")
 var dynLink = $('<a href=abc.html"'>LEather</a>');
    $("#xyz").append(dynLink);

Thanks!

Gorgeous
  • 47
  • 1
  • 6
  • 2
    [What have you tried?](http://whathaveyoutried.com) – Derek 朕會功夫 May 30 '12 at 02:37
  • possible duplicate of [Alternative to a million IF statements](http://stackoverflow.com/questions/10029089/alternative-to-a-million-if-statements) - I've posted a general answer there (covering all the answers here :-). – Bergi May 30 '12 at 03:58

4 Answers4

2

You could try this:

var link = [
    ["#abc", "#wfh", "http://www.123.com", "Maine"],
    ["#123", "#qwe", "http://www.abc.com", "Texas"]
];

$.each(link, function(e) {
    $(link[e][0] + "," + link[e][1])
        .append("<a href='" + link[e][2] + "'>" + link[e][3] + "</a>");
});​

Example: http://jsfiddle.net/Yvuvh/5/


This is just simply setting up the links and titles in the array, and a for loop is searching through the array to see if it can find a div with any of those id's, and if so, then append the appropriate link.

To add more, just add another array to the link array, like so:

var link = [
    ["#abc", "#wfh", "http://www.123.com", "Maine" ],
    ["#123", "#qwe", "http://www.abc.com", "Texas" ],
    ["#xyz", "#zyx", "http://www.yzx.com", "Mexico"]
];​
Shaz
  • 15,637
  • 3
  • 41
  • 59
  • 1
    pardon my ignorance but where are you checking the ID of each div before inserting a link in it? – Gorgeous May 30 '12 at 03:07
  • Oh I now understand the code. This is beautiful. How can I mark two answers correct? I upvoted you :) – Gorgeous May 30 '12 at 03:13
  • just one more question - how can I add an 'OR' condition..like if div.id = abc OR div.id = 123 then // do this – Gorgeous May 30 '12 at 03:17
  • @Gorgeous You can't unfortunately. So just always remember to mark the answer you feel most comfortable with and answers the question. :) – Shaz May 30 '12 at 03:18
  • I just updated your code but "wfh" does not work. Any idea? http://jsfiddle.net/Yvuvh/1/ – Gorgeous May 30 '12 at 03:32
  • @Gorgeous Updated answer. Try the new link above. – Shaz May 30 '12 at 03:52
  • @Shaz: Passing a function (which returns undefined in the most cases) to append() for each link array is not a good solution in here. – Bergi May 30 '12 at 04:07
  • @Bergi How's the new solution then? Less `Undefined` happening. – Shaz May 30 '12 at 04:23
  • Bergi what does that mean, please explain in simple language – Gorgeous May 30 '12 at 04:28
  • @Shaz: Better. You could further improve it by allowing different numbers of ids - just make it one selector at the first array index. – Bergi May 30 '12 at 04:29
1
if $("#abc) then

 var dynLink = $('<a href=zzz.html"'>Cosmetics</a>');
    $("#abc").append(dynLink);

else if $("#xyz")
 var dynLink = $('<a href=abc.html"'>LEather</a>');
    $("#xyz").append(dynLink);

▲ That is not valid JavaScript.


▼ This is how you do it when you have a bunch of if-thens:

switch(div.id){
    case "abc":
        $('<a href="zzz.html">Cosmetics</a>').appendTo("div#whateveritis");
        break;
    case "xyx":
        $('<a href="abc.html">Leather</a>').appendTo("div#whateveritis");
        break;
    case "more more more":
        //same stuff here.
        break;
    default:
        //default
        break;
}

Very self-explanatory for beginners. ;)

Seriously, you should start looking through stuff in MDN MDN. It is a good place for JavaScript references and demos (examples).

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Derek thanks for first showing me some code and then providing a link where I can learn to write this kinda code. I will study the switch-case statement in detail. This looks similar to what I have used in Java – Gorgeous May 30 '12 at 03:08
1

Create an object that contains all of these relationships, like this:

var links = {
    'abc': { link:'foo.html', text:'Foo Link' },
    'xyz': { link:'bar.html', text:'Bar Link' }
};

Then we'll add a couple div elements to test this out:

​<div id="abc"></div>
<div id="xyz"></div>​​​​​​​​​​
<div id="foo"></div>

And lastly our jQuery which should add some links for us:

$("div").append(function(){
    var link = links[this.id];
    return link ? $("<a>", { href:link.href, html:link.text }) : "n/a" ;
});​​​

This cycles over all of our div elements, checking to see if their id is found within our links object. If it is, then we place a link within that div that has the appropriate properties. If we don't find that id within our object, we simply append "n/a" to the div.

<div id="abc"><a href="foo.html">Foo Link</a></div>
<div id="xyz"><a href="bar.html">Bar Link</a></div>
<div id="foo">n/a</div>

Demo: http://jsfiddle.net/vFjSw/

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • Jonathan, a very good solution, but performance wise how do I determine if your solution or Shaz solution performs better? – Gorgeous May 30 '12 at 04:27
0

Put the div.id's in an associate array that maps to the target URL, then just look it up by key. One hashed lookup beats a linear number of if/else-if comparisons if you only have to load it once for each lookup...

This strikes me as more "elegant" or readable or maintainable regardless of micro-performance. It's not obvious to me which of make array v. run if/else if's is faster, you'll have to profile. If however, you 1) must optimize for time, and 2) only expect one use of this code for each time the page is loaded, the best you can do is put the url's you expect toward the top of the if/elif block. Be sure to comment exactly that you're doing this so future dev doesn't alphabetize them.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 2
    thanks but I am so new to scripts that it went over my head..can you show some code please – Gorgeous May 30 '12 at 02:43
  • Why are you here on StackOverflow then? This is a place where beginners like me can learn right? And I did try, not a homework I am asking you to do. – Gorgeous May 30 '12 at 03:11