0

I'm currently attempting to write a dynamic table where the heading width is split in equal widths equally across the required number of columns (PHP variable "$numberofcolumns").

Firstly, could someone please give me a hand popping some more code in that would make it easy for me to calculate the table heading widths dynamically? So far I have only got as far as turning the php variable into a JavaScript variable $noofcolumns -> var columnno as shown below - I'm now completely lost!

My total table width remaining to use is 80% (20% already used for a fixed width column).

i.e.
if columnno = 3 -> table heading width = 80% / 3
if columnno = 4 -> table heading width = 80% / 4
etc...

I have tried using the calc() CSS3 function previously, but this doesn't display correctly in a fair amount of browsers! (hence the requirement for javaScript!) Due to this issue, it would be easier if the outcome of the JavaScript code gave a value in pixels!

<script type="text/javascript">
var columnno = <?php echo $numberofcolumns; ?>;
</script>

Secondly, am I correct in thinking that I can retrieve the calculated JavaScript variable (as javaScript is client side...) by using a PHP function such as: $_REQUEST['javascript_variable_name_here']?

1 Answer 1

0
<script type="text/javascript">
var columnno = <?php echo $numberofcolumns; ?>;
var headingWidth = Math.floor(80 / columnno);
var lastHeadingWidth = 80 - headingWidth;

// now you assign these values to your columns. I'd suggest you use jQuery, assign a class to each column (col1, col2, etc., using PHP), and then:

// we assume i = 1 is that 20% fixed column
for(i = 2; i < columnno; i++) {
    $('.col' + i).css('width', headingWidth + '%');
}
$('.col' + columnno).css('width', lastHeadingWidth + '%');
</script>

Why Math.floor and lastHeadingWidth? If you divide 80 by 3 and then multiply the result by 3 you'll find out you are missing 0.0000000000001 pixels (it's all about internal number representation and precision). Also, some browsers automatically round float values to 3-4 decimal places, so accounting for this difference yourself is more consistent. Yes, for odd column numbers the last one will be slightly larger.

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

2 Comments

You are not right about $_REQUEST. $_REQUEST is an array containing $_POST + $_GET + $_COOKIE. If you need something sent from browser to server you need to send it using a HTTP request. Look into AJAX.
Thank you very much! Will look into AJAX then!

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.