How to pass variable to href in javascript?

北战南征 提交于 2019-11-30 03:14:29

问题


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

回答1:


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



回答2:


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;



回答3:


Try this:

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

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



回答4:


Try this:

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



回答5:


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


来源:https://stackoverflow.com/questions/20769299/how-to-pass-variable-to-href-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!