我如何从datalist获得价值

时间:2017-09-02 13:09:09

标签: javascript php html

我在获取客户名称时遇到问题。我在php上有这个代码

<label>Select Customer :</label>
<input list="customer_list" id = "s_cust" name = "s_cust" type="text" onblur ="setCustName();">
<label id="cust_name" name = "cust_name"></label>
<datalist id="customer_list">
<?php
    $result= $mysqli->query("SELECT * FROM tbl_customers");
    while ($row = $result->fetch_assoc()) {
        echo "<option value = 
".$row['CustomerID'].">".$row['FirstName']." ".$row['MiddleName']." 
".$row['LastName']."</option>";
    }
?>
</datalist>

我有一个javascript

function setCustName() {
  document.getElementById('cust_name').innerText = document.getElementById('customer_list').value;
}

我想要做的是根据datalist获取所选值。我尝试了这段代码但给了我未定义的数据。帮帮我。

1 个答案:

答案 0 :(得分:1)

使用s_cust代替customer_list,实际上您正在为ID为s_cust

的元素赋值

&#13;
&#13;
function setCustName()
{
  var val = document.getElementById('s_cust').value;
  if(val.trim() != ""){
      var opts = document.getElementById('customer_list').childNodes;
      for (var i = 0; i < opts.length; i++) {
        if(opts[i].value !== undefined){
          if (opts[i].value === val) {
              document.getElementById('cust_name').innerText = opts[i].innerText;
            break;
          }
        }
      }
    }else{
        document.getElementById('cust_name').innerText = "";
    }
}
&#13;
<label>Select Customer :</label>
         <input list="customer_list" id = "s_cust" name = "s_cust" 
type="text" onblur ="setCustName();">
        <label id="cust_name" name = "cust_name"></label>
        <!-- <input list="browsers"> -->

<datalist id="customer_list">
  <option value = "11" onclick="alert('test')"> Internet Explorer </option>
  <option value = "12"> Firefox </option>
  <option value = "13"> Chrome </option>
</datalist>
&#13;
&#13;
&#13;