Capturing HTML Input field value with Javascript

Back


Capturing or collecting the input fields from an HTML field is not that difficult with a little help from Javascript that is and IF you wanted or need to update your MySQL database from behind the scene you can do so with Ajax.

I normally use a simple Ajax library (which you can download for free on the Net) that help me do just that.

The following sample code works and the key parts are as shown here on this page and as follows:

Files You need, to work with AjaxQ

  • ajaxqconfig.php
    • this is where you configure your database name, user name, password, server
    • this is just text
  • ajaxq.php
  • ajaxq.js

Note:

  • document.getElementById("ItmName").value = row["ItmName"];
    • please note that the value coming from row["ItmName"] is html formatted
    • the normal .innerHTML was not used
  • onchange="kuha_No(ArtNo);"
    • ArtNo is the input field
    • act as a pass-by value to the javascript function kuha_No

In this sample, I have fetch values from a database table and placed them or reassign them to other HTML Input field, which happens to be a product Name and a product Description.

IF the said product does not exist at all, then none will be placed in those fields (ItmName and ItmDescp), they will be blank.

Javascript you need to include

<script src="ajaxq.js" type="text/javascript" > </script>

Please note that, the file ajaxq.js should be on the root or   IF you have a sub-folder you may need to have this there as well too.

sample code with ajaxQ

<script type="text/javascript">

   var usr_art_no = "";

   function kuha_No(uartno)
   {
     var sqlko = "";
     usr_art_no = uartno.value;
    
     myajaxQ2 = new ajaxQ;
     sqlko = "select ItmName, ItmDescp from tbl_accessories where"+
          " ArtNo = '" +
          usr_art_no +
          "'";

     resti = myajaxQ2.sqlQuery(sqlko);

     row = myajaxQ2.fetchAssoc(resti);

     document.getElementById("ItmName").value = row["ItmName"];
     document.getElementById("ItmDescp").value = row["ItmDescp"];
   }

Input field side <input name="ArtNo" type="text" class="textfieldChngPass" id="ArtNo" onchange="kuha_No(ArtNo);">