Daniel
Daniel

Reputation: 87

Include html based on li tag's id in JQuery

I've got a script that I want to include a html file based on the list item's id.

I've got two list items

<ul class="fruits">
         <li id="0">Apples</li>
         <li id="1">Pears</li>
</ul>

Now here's my script so far. Basically I want to check the id of the selected list item and insert a html file with a description of that fruit.

Script is

$(document).ready(function() {
$(".fruits li").click(function() {
                if(this.id == "0") {
                    $(".fruit_copy").load("blocktext/apple.html");
                }
        });
});

And I want this <div class="fruit_copy"> </div> to be populated with the HTML content. But of course it's not working.

Upvotes: 2

Views: 204

Answers (3)

enguerranws
enguerranws

Reputation: 8233

You could do something cleaner, like that :

HTML part :

<ul class="fruits">
         <li data-dest="blocktext/apple.html">Apples</li>
         <li data-dest="blocktext/pears.html" >Pears</li>
</ul>

JS part :

$(document).ready(function() {
  $(".fruits li").click(function() {
     // you don't need IDs or if/else statement.
     var dest = $(this).attr('data-dest');
     $(".fruit_copy").load(dest);
   });
});

Upvotes: 1

imbondbaby
imbondbaby

Reputation: 6411

Try this:

$(document).ready(function () {
$(".fruits li").click(function () {
    if ($(this).attr("id") == "0") {
        //alert("aa");
        $(".fruit_copy").load("blocktext/apple.html");
    }
    });
});

Assuming your relative path is correct.

Also, in HTML 5 you can use ID's as numbers but HTML 4 is strict on it.

EDIT - Thanks to MiniRagnarok for the link in comments

Credits: https://stackoverflow.com/a/79022/3739658

For HTML 4, the answer is technically:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Upvotes: 0

MackieeE
MackieeE

Reputation: 11862

  • The options values are "falsey", they're strings whilst you're checking integers, help it by adding .toString():

We also append the === so we're not type checking - string to string.

if ( this.id.toString() === "0" ) {
   //Code
}
  • Lastly, check your console & use the network tab to see if your script is successfully collecting the .html file with a 200 HTTP code.

Upvotes: 0

Related Questions