1

I'm having a problem on getting the customer's name. I have this code on 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>

and I have a javascript

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

I want to do is get the selected value based on the datalist. I tried this code but giving me undefined data. Help me Guys.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
jay r bayog
  • 53
  • 2
  • 8

1 Answers1

1

Use s_cust instead of customer_list, Actually you are putting value to the element whose id is s_cust

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 = "";
    }
}
<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>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109