tags:

views:

40

answers:

2

Hi,

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>

A: 

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.

scunliffe
One word of advice, styling attributes and tags are deprecated. Use style instead.
Ben
@Ben - I would agree, although getting the exact behavior you want using CSS in IE may lead to some frustration.
scunliffe
+1  A: 

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.

Anriëtte Combrink
Keep in mind Kristina that the "4" would be replaced with whatever percentage you see fit.
Jeff
Yes, he's right, thanks Jeff. :)
Anriëtte Combrink
thank you for your help. Much appreciated
kristina