简体   繁体   中英

how to get the value from textbox in table and update it using javascript

 <!DOCTYPE html> <script> function m(){ var tb=document.getElementById("w"); var len=tb.rows.length; var b=[]; for(var i=1;i<len;i++) { b[ i ] = parseInt( tb.rows[ i ].cells[ 4 ].querySelector('input').value ) * parseInt( tb.rows[ i ].cells[ 5 ].querySelector('input').value ); document.getElementById("w").rows[i].cells[6].innerHTML=b[i]; } } </script> </body> </html> 

I am new to javascript!I tried getting value from textbox in the table and updating the linetotal dynamically but i am getting the output as NaN. can anybody corrects the error !!

You are trying to access .value on a table cell. You need to access the input field inside the table cell.

You need to be using .querySelector('input').value instead of just .value

b[ i ] = parseInt( tb.rows[ i ].cells[ 4 ].querySelector('input').value ) * parseInt( tb.rows[ i ].cells[ 5 ].querySelector('input').value );

I really recommend using jQuery though. It'll make life a whole lot easier! Vanilla Javascript is difficult to work with and maintain - even for the best developers.

function m(){
  var tb=document.getElementById("w");
    var len=tb.rows.length;
    var b=[];
    for(var i=1;i<len;i++) {
      var qty = tb.rows[i].cells[4].querySelector('input').value,
          price =  tb.rows[i].cells[5].querySelector('input').value;
      console.log(qty);
      if(qty != "" && price != "") {
        b[i]=parseInt(qty)*parseInt(price);
      } else {
        b[i] = "None";
      }
      tb.rows[i].cells[6].innerHTML=b[i];
    }
  }

You need to use querySelector('input').value instead of .value . I added a if statement that checks if both fields not are null and if so, the result will be "Null". You can edit the "fail-string" to whatever you want to.

Check this out: https://jsfiddle.net/abhiphirke/joq3jLk5/3/

Fill in values in fields and then hit Click Me! button. If you dont, you'd get NaN. Have fun!!

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