Search code examples
jqueryurlparametershref

Change/Replace Href parameter with jquery


I have a URL parameter that I want to replace based on whether a checkbox has been checked:

<input id="acknowledge" type="checkbox" checked="checked" name="acknowledge" tabindex="">I accept

<a href="p_add_institution?id=55&p_acknowledge=Y" class="stronglink" id="add-institution">Add another institution</a>

I want to replace p_acknowledge parameter to be p_acknowledge=N if the checkbox is not checked and p_acknowledge=Y if it is checked.

It always return p_add_institution?id=55&p_acknowledge=Y even if the checkbox is not checked.

Also, when I hover over the link, I want to have the proper URL showing up as well.

http://jsfiddle.net/u89usjnj/5

Any help would be appreciated and if anyone can explain why it the parameter is not switching to N

Thanks


Solution

  • // Input with id acknowledge on change event
    $("input#acknowledge").change(function(){
    
        // Fetch checkbox is checked or not
        var status = this.checked;
    
        // Decide what to set in href Y or N based on status
        var yorn = (status?"Y":"N");
    
        // Update the link using .attr
        $("#add-institution").attr("href", "p_add_institution?id=55&p_acknowledge="+yorn);
    })
    

    Play Here

    FYI:

    Rule of thumb is: .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method. (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)