简体   繁体   中英

Get input value javascript

I'm trying to write some input in an HTML element and get the input text using JS, and after that send the value to another file using AJAX, but it's not working and i get only "null" as result

is there a reason?

this is my HTML

<button type="button" onclick="loadDoc()">Value</button>
     <input type="number" class="test" id="test" name="test" value="" style="width:10%" >
     <div id="mostraAttuale"></div>
    </br>

this is my JS function

function loadDoc() {
    var value = document.getElementById("test");
    alert(value);
    var url = <?php echo json_encode($test); ?>;
    var email = <?php echo json_encode($mail); ?>;
    var valuereq = new XMLHttpRequest();
    valuereq.open("GET", url+'?email='+email+'&value='+value, true);
    valuereq.send();
    valuereq.status;
    valuereq.onreadystatechange = function () {
        if (valuereq.readyState == 4 && valuereq.status == 200) {
            var return_data = valuereq.responseText;
            document.getElementById("mostraAttuale").innerHTML = "ultimo valore inserito: " + return_data;
        }
        else document.getElementById("mostraAttuale").innerHTML = valuereq.status;
    }
    document.getElementById("test").value="";
}

Thank you in advance.

Try this:

function loadDoc() {
    var value = document.getElementById("test").value;
    alert(value);
    var url = "<?=json_encode($test) ?>";
    var email = "<?=json_encode($mail) ?>";
    var valuereq = new XMLHttpRequest();
    valuereq.open("GET", url+'?email='+email+'&value='+value, true);
    valuereq.send();
    valuereq.status;
    valuereq.onreadystatechange = function () {
      if (valuereq.readyState == 4 && valuereq.status == 200) {
          var return_data = valuereq.responseText;
          document.getElementById("mostraAttuale").innerHTML = "ultimo valore inserito: " + return_data;
      }
      else 
         document.getElementById("mostraAttuale").innerHTML = valuereq.status;
    }
    document.getElementById("test").value="";
}

The line var value = document.getElementById("test"); doesn't get the value but the "HTMLInputElement". Replace it by :

 var value = document.getElementById("test").value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM