0

This is a take off from the following solved questions (so please don't tag this as duplicate):

  1. jquery: access value of a textbox in datatable

  2. Event binding on dynamically created elements?

I created a dynamic textbox in a datatable. Now, I need to access that value to compute a new value upon keypress. While I find the answers on (Event binding on dynamically created elements?) extremely useful, I am still at lost how to get value of the textbox.

The "keyup change" function is already triggered since I am getting the alert. However, I am getting a 'NaN' (not a number) value. Please help!

this is my code:

var xindex;
var yindex;

 $(document).on('mouseover', '#table1 tr', function() {
     xindex = this;
     yindex = this.rowIndex;
 });


 var dtable = $('#table1').DataTable();
 var origval = $('#table1 tr:eq(' + parseInt(yindex) + ') >td:eq(' + 1 + ')').html(); 
//this is the original value in which I would like to add the adjustment
 var textvalue = $(yindex).find(".txtval");
   //upon creating the datatable dynamically, the class of the input textbox is "txtval"
 var newval;

 $(document).on('keypress', '.textvalue', function(e) {
    if (e.which != 8 && e.which !=0 && (e.which < 48 || e.which > 57)){
        e.stopImmediatePropagation();

    return false;
    }


    }).on('keyup change', function(e) {

        newval = origval + this.value;
        alert(newval);
 });
Community
  • 1
  • 1
lulutanseco
  • 313
  • 1
  • 8
  • 29

2 Answers2

0

In your function, this is the document. this.value doesn't have sence if you want the text in your textbox.

This is my chrome console : $(document).on('keypressed', 'body', function (e) { return false }).on('keyup change', function(e) { console.log(this) });

returns me [document]

Titouan56
  • 6,932
  • 11
  • 37
  • 61
0

By luck, I was able to resolve the issue by declaring the variables globally (and inserting the value upon datatable mouseover event). Please see the following code (and if you can help me improve/clean the code, I implore you, please do so. thank you)

var xndex;
var yindex;
var origval; 
var newval;

$(document).on('mouseover', '#table1 tr', function() {
     rndex = this;
     jindex = this.rowIndex;

     origval = $('#table1 tr:eq(' + parseInt(yindex) + ') >td:eq(' + 1 + ')').html();

 });


$(document).on('keypress', '.txtval', function(e) {
     var mvalue = jQuery(xndex).find(".txtval").val();
     //value to be added to origval


    if (e.which != 8 && e.which !=0 && (e.which < 48 || e.which > 57)){
        e.stopImmediatePropagation();
      //to trap non-numeric characters
    return false;


    }).on('keyup change', function(e) {

        newval = parseFloat(origval) + parseFloat(mvalue);
        alert(newval);
 });

enter image description here

lulutanseco
  • 313
  • 1
  • 8
  • 29