2

I have a javascript object and an html table.

     var myObj = [
 {
           price: 1,
           label: "One"
        }
     ];
<table>
  <tr>
    <th id = "price">100</th>
    <th id = "label">product</th>
  </tr>
  <table>

Is it possible to insert the table values in the object?

In order to have updated properties

{
price: 100,
label: "product"
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Bill
  • 162
  • 1
  • 9
  • Just a comment about your use of "id". Ids are unique. You should not use them if you intend to manage several rows. Is it so ? – Amessihel Apr 23 '15 at 15:29

2 Answers2

5

Do you mean

myObj.price=parseInt(document.getElementById("price").innerHTML,10);

for integers or

myObj.price=parseFloat(document.getElementById("price").innerHTML);

if price has decimals

and for the label:

myObj.label=document.getElementById("label").innerHTML;

Please note that .innerHTML is compatible with older browsers - if you do not need to support them, use .textContent instead

Like

var myObj = [
 {
           price: 1,
           label: "One"
        }
     ];
window.onload=function() {
  myObj.price=parseInt(document.getElementById("price").innerHTML,10);
  myObj.label=document.getElementById("label").innerHTML; 
  window.console&&console.log(myObj)
}
<table>
  <tr>
    <th id = "price">100</th>
    <th id = "label">product</th>
  </tr>
  <table>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

Considering this code :

<table>
  <tr>
    <th id = "price">100</th>
    <th id = "label">product</th>
  </tr>
<table>

To get these values :

document.getElementById("price").nodeValue;
document.getElementById("label").nodeValue;

See Jsfiddle here.

Then to convert the amount as integer, use parseInt(string). As float values (it's an amount), use parseFloat(string).

Instead of nodeValue you can use textContent, data or wholeText. Check this to know more and to fit your needs.

Community
  • 1
  • 1
Amessihel
  • 5,891
  • 3
  • 16
  • 40