简体   繁体   中英

Javascript input field value

Need to get the value of input field inside script tag.

I need to get a value of input field that append to the html table using script tag. My code is following

function myFunction(i) {
  $.ajax({
    url: "<?php echo base_url(); ?>admin/itemD",
    type: "POST",
    dataType: "json",
    data: {
      "itID": i
    },
    success: function(data) {
      //console.log(data);
      if (data[0].availability == 0) {
        alert('Item Not Available');
      } else {
        var tr = "<tr>";
        var td0 = "<td>" + (i + 1) + "</td>";
        var td1 = "<td>" + data[0].item_name + "</td>";
        var td2 = "<td>" + data[0].price + "</td>";
        var td3 = "<td><input placeholder='Advance'  class='form-control col-3' /></td>"
        $("#myTable").append(tr + td0 + td1 + td2 + td3);
      }

    },
    error: function(err) {
      console.log(err);
    }
  });
}

This is my code I used this code to show some data set which get from clicking event. But now I need to add input field to my javascript code. So I add input field to my code.

var td3 = "<td><input placeholder='Advance' id='vale' class='form-control col-3' /></td>"

But how do I get this input field value? I tried to get the value of this input field by adding

document.getElementById('vale');

But It does not work. I go though the every problem earlier posted in stackoverflow. But no problem matching with my problem.

One way to achieve this might be to update your success handler, by binding an event handler via say, keyup() , that queries the current value of the input field when a key is pressed while the field is focused:

success: function(data) {
      //console.log(data);
      if (data[0].availability == 0) {
        alert('Item Not Available');
      } else {
        var tr = "<tr>";
        var td0 = "<td>" + (i + 1) + "</td>";
        var td1 = "<td>" + data[0].item_name + "</td>";
        var td2 = "<td>" + data[0].price + "</td>";
        var td3 = "<td><input placeholder='Advance'  class='form-control col-3' /></td>"
        $("#myTable").append(tr + td0 + td1 + td2 + td3);
      }

      // Select the input field for the table, and add a keyup event listener 
      // to it
      $('input', '#myTable').keyup(function() {

          // Access the current value of the field like so
          var currentFieldValue = $('input', '#myTable').val();
          alert( 'Value of input is: ' + currentFieldValue );
      })
    }

You need to add id='vale' attributes which is not available in your input tag

After that you can get value by like this:

document.getElementById('vale').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