Moxie C
Moxie C

Reputation: 442

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

Upvotes: 1

Views: 6242

Answers (2)

Stan Shaw
Stan Shaw

Reputation: 3034

To answer the question as it was asked:

$("#acknowledge").on("change", function(){
    $("#add-institution").attr("href", "p_add_institution?id=55&p_acknowledge=" + $(this).prop("checked") ? "Y" : "N");
});

However, you could also create two links and just toggle their display, accordingly:

HTML:

<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_Yes">Add another institution</a>
<a href="p_add_institution?id=55&p_acknowledge=N" class="stronglink" id="add-institution_No" style="display:none;">Add another institution</a> //Hidden by default

JQuery:

$("#acknowledge").on("change", function(){
    if ($(this).prop("checked")){
        $("#addinstitution-Yes").show();
        $("#addinstitution-No").hide();
    }
    else{
        $("#addinstitution-Yes").hide();
        $("#addinstitution-No").show();
    }
});

Upvotes: 0

void
void

Reputation: 36703

// 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/)

Upvotes: 2

Related Questions