Search code examples
jqueryruby-on-railshref

setting href attribute with jquery


here is my code:
(note: I'm using Purl (https://github.com/allmarkedup/purl))

$("#major").click(function() {
        $(".questions, .sections, #major_list").hide();
        $(".subnav_item:not(#major)").css("font-style", "normal");
        $("#major").css("font-style", "italic");
        $(".subnav_item:not(#major)").css("color", "black");
        $("#major").css("color", "#6666FF");
        $("#major_list").show();
        var a = 0;
        original_link = [];
        $(".major_question").each(function() {
            original_link[a] = $(this).attr("href");
            a++;
        });
    });
        $("#major_list li").click(function() {
            $("#major_sub").text($(this).text());
            $("#major_nav .questions").hide();
            $("#major_nav .questions").show("fast");
            major = $(this).text();
            major = major.toLowerCase();
            major = major.replace(" ", "-");
            var i = 0;
            $(".major_question").each(function() {
                link = original_link[i];
                i++;
                link = url.attr('host') + "/" + url.segment(1) + "/academics/" + major + "/" + link;
                alert(link);
                $(this).attr("href", link);
            });
        });

Say I am on the page http://localhost:3000/university-of-pittsburgh/academics/classes/do-kids-participate-in-class. When I alert(link)... the correct link is alerted!!! But when I click the link, it gives me the correct link preceded by... http://localhost:3000/university-of-pittsburgh/academics/classes.

  1. Why on earth is this?
  2. How do I correct this?

Solution

  • Place a froward slash "//" in front of you links otherwise they become relative to the current page. For example:

    link = url.attr('host') + "/" + url.segment(1) + "/academics/" + major + "/" + link;
    

    would become

    link = '//' + url.attr('host') + "/" + url.segment(1) + "/academics/" + major + "/" + link;