Search code examples
javascriptdrop-down-menuhrefdom-eventsonchange

Javascript href change on onChange event


I got the below script:

function sele(dropdownlist, button)
{
    var url = dropdownlist.value;
    if (url !== "")
    {
        button.href = url;
    }
    if  (url === "null")
    {
        button.href = 'javascript:void(0)';
    }
 }

The button id is passed by 'button' variable. This script do not pass href to any button. How to make sure the href is changed in the correct button?


Solution

  • Button element does not have href attribute. Thus, you might want to do the following:

    <button id="your_button"> <a id="to_change_url" href="www.hello.com"> 
                              an example </a> </button>
    

    Now, rather than trying to access button.href( which should result in error, I think), you can change the anchor element in button. Easy way might be something like this:

        var href_to_change=document.getElementById("to_change_url");
        href_to_change.href="WHATEVER URL YOU WANT TO CHANGE TO";