GetElementByID returns null value


GetElementByID returns null value

我正试图使用javascript为我的项目添加验证,但如果我使用GetElementByID函数,我的javascript函数不会返回值。因此,我的php脚本如下:

<select name="IDDep" style="width:152px" onClick="getListaDep()"> 
    //blah blah
</select><span></span>
<div id="divDep">

重要的是点击

我的javascript:

function getListaDep( ) {
        var IDDep ;
        IDDep= document.getElementById(IDDep).value;
        var strURL="ajax_page/findDepTranz.php?&IDDep="+IDDep;
        var req = getXMLHTTP();     
        if (req) {          
            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {            
                        document.getElementById('divDep').innerHTML=req.responseText;   
                    } else {
                        alert("There was a problem while using XMLHTTP:'n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }               
    }

findDepTranz.php

<?php
$IDDep = intval($_GET['IDDep']);
?>
<div>
    <?php echo 'IDDep: '.$IDDep; ?>
</div>  

这个例子没有返回IDDep,但如果我把它放在javascript:中:onClick="getListaDep(this.value)"

 function getListaDep(IDDep ) {             
        var strURL="ajax_page/findDepTranz.php?&IDDep="+IDDep;
.... if works.

我需要返回两个类似IDDep的值,而我的document.getElementById(IDDep).value不起作用。有什么建议吗?

您需要引用ID:

IDDep= document.getElementById('IDDep').value;

您还需要更改select,使其具有ID:

<select name="IDDep" id="IDDep" style="width:152px" onClick="getListaDep()"> 
                     ^^^^^^^^^^

尝试以下操作:更改

IDDep = document.getElementById(IDDep).value;

IDDep = document.getElementById('IDDep').value; //Quoting the id

<select name="IDDep" style="width:152px" onClick="getListaDep()"> 

<select name="IDDep" style="width:152px" onClick="getListaDep()" id="IDDep">

然后在javascript中执行以下

document.getElementById('IDDep').addEventListener('change', function() {
   //Your function here
});
//You can change 'change' to 'click' aswell if you need to

这也允许您删除onclick-so

<select name="IDDep" style="width:152px" onClick="getListaDep()" id="IDDep">

成为

<select name="IDDep" style="width:152px" id="IDDep">