How to pass variable to href in javascript?

user3120060 picture user3120060 · Dec 25, 2013 · Viewed 63k times · Source

How to pass this variable value here? Below code is not working. And all other discussions on Stackoverflow are unclear.

<script type="text/javascript">
        function check()
        {
            var dist = document.getElementById('value');
            if (dist!=""){
                window.location.href="district.php?dist="+dist;
            }
            else
               alert('Oops.!!');
        }
</script>

And my HTML code is:

<select id="value" name="dist" onchange="return check()">

Answer

Dhaval Marthak picture Dhaval Marthak · Dec 25, 2013

You have to fetch field value using .value as you are passing whole object to the URL as document.getElementbyId('value') returns whole field object.

var dist = document.getElementById('value').value;

So your function should be like this

function check() {
    var dist = document.getElementById('value').value; // change here
    if (dist != "") {
        window.location.href = "district.php?dist=" + dist;
    } else
        alert('Oops.!!');
}