kristina
kristina

Reputation: 61

dynamical change td width with js

I need to change the width of a td using javascript. The value of the width will be pulled in and then I need to multiple it to get a percentage. I just need to know how to write the js so far I have got to here but it is not working

<script language="JavaScript">
var divWidth = 66*0.4;

document.write("<td width="+divWidth+">");

document.getElementById("myRow").write("<td width="+divWidth+">");

</script>


<table>
<tr>
    <td id="myRow"></td>
</tr>

Upvotes: 2

Views: 13020

Answers (2)

Anri&#235;tte Myburgh
Anri&#235;tte Myburgh

Reputation: 13517

Try using jQuery, it's a Javascript library/framework and what you're trying to do above will be ten times easier using jQuery.

With jQuery, your code will be:

$(document).ready(function () {
    var newWidth = $("#myRow").width();
    $("#myRow").width(newWidth*0.4);
}

//edit:

Sorry, I had the multiple wrong.

Upvotes: 2

scunliffe
scunliffe

Reputation: 63588

I think you want this:

<script type="text/javascript">
  var divWidth = 66*0.4;
  document.getElementById("myRow").setAttribute('width', divWidth);//defaults to pixels
  //or if you really want this as a percentage
  document.getElementById("myRow").setAttribute('width', divWidth+'%');//percent
</script>


<table>
  <tr>
    <td id="myRow"></td>
  </tr>
</table>

However, there are some things I would adjust in your code. I changed the language attribute in the script tag (now deprecated) to a type="javascript". The id on your TD element is myRow I would change this to something reflecting the cell vs. the row.

Upvotes: 3

Related Questions