user3120060
user3120060

Reputation:

How to pass variable to href in javascript?

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()">

Upvotes: 14

Views: 97755

Answers (6)

Steven Spungin
Steven Spungin

Reputation: 29189

I use a very different approach to this. I set browser cookies in the client that expire a second after I set window.location.href.

This is way more secure than embedding your parameters in the URL.

The server receives the parameters as cookies, and the browser deletes the cookies right after they are sent.

const expires = new Date(Date.now() + 1000).toUTCString()
document.cookie = `oauth-username=user123; expires=${expires}`
window.location.href = `https:foo.com/oauth/google/link`

Upvotes: 1

Prateek
Prateek

Reputation: 6975

Try this:

var dist = document.getElementById('value').value;
if (dist != "") {
 window.location.href="district.php?dist="+dist;
}

Upvotes: 3

Dinesh
Dinesh

Reputation: 4110

You have to make some correction in your function..

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

Upvotes: 1

Evgeny Samsonov
Evgeny Samsonov

Reputation: 2750

Try this:

function check() {
    var dist = document.getElementById('value').value;

    if (dist) {
        window.location.href = "district.php?dist=" + dist;
    } else {
        alert('Oops.!!');
    }
}

Upvotes: 4

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

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.!!');
}

Upvotes: 18

Satpal
Satpal

Reputation: 133453

You have fetch value of the field, Currently you are using DOM object

Use

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

OR

Use

 if (dist.value!=""){
     window.location.href="district.php?dist="+dist.value;

instead of

if (dist!=""){
     window.location.href="district.php?dist="+dist;

Upvotes: 6

Related Questions