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"
}
1
  • 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 ? Commented Apr 23, 2015 at 15:29

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.