user3224813
user3224813

Reputation: 85

Use dropdown value for a href link

I try to use a dropdown value for a href link with no success.

function GetSelectedValue(){
    var e = document.getElementById("EquipeLabel");
    var result = e.options[e.selectedIndex].value;
    
    document.getElementById("result").innerHTML = result;

}
<head>  
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/4.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
    <style>
        body {
          background-color: #ffcccc; 
          width:500px;
          margin:0 auto;
        }
    </style>
</head>

<body>
    <br/>
    <table border="0">
        
        <tr> 
            <div class="input-group mb-3">
            <div class="input-group-prepend">
            <span class="input-group-text" id="D_username">Equipe :</span>
            </div>
            <select class="custom-select" name="Equipe" id="EquipeLabel" onchange="GetSelectedValue()">
                <option value="">--Select--</option>
                <option value="Team1">Team1</option>
                <option value="Team2">Team2</option>
                <option value="Team3">Team3</option>
                <option value="Team4">Team4</option>
            </select>
        </tr>
        <tr>
            <td><a href="Action.php"onclick="location.href=this.href+'?Equipe='+result;return false;"> Find </a> </td>
        </tr>
    </table>

</body>

the link url generate is something like this

....Action.php?Equipe=[object%20HTMLParagraphElement]

and I need this

...Action.php?Equipe=Team2

Upvotes: 0

Views: 75

Answers (1)

Bouke
Bouke

Reputation: 1577

You are assigning the selected option to a DOM element with id result, which doesn't exist. The GetSelectedTeam function should return the selected team or open the link directly (renaming the function to OpenSelectedTeam to reflect what is actually does), as displayed in the code below.

function OpenSelectedTeam() {
    var e = document.getElementById("EquipeLabel");
    var selectedTeam = e.options[e.selectedIndex].value;
    window.location.href = window.location.href +'?Equipe=' + selectedTeam;
}

The related HTML hyperlink should be like this:

<a onclick="OpenSelectedTeam()"> Find </a>

The onclick event on the select list should be omitted, depending on what you want, navigate immediately after changing the selected team, or only when clicking the link.

Using a regular form might be a more appropiate solution however.

Upvotes: 1

Related Questions