Search code examples
phpjqueryhtmlcsscss-counter

Is it possible to have a text box with CSS Counter increment value?


I have created a dynamic table, with PHP and jQuery and am using CSS for creating auto increment Serial Number.

This is the code

Requirement:

At the moment, the column in which the serial numbers are auto generated are blank. Is it possible to add a text box in which the serial numbers are generated so that the values can be retrieved while being saved?

That is, instead of having :

content: counter(serial-number);

we have something like this :

content: counter(text); 

Or is there any possible way to save the serial numbers in a text box to be saved in the database.

Any suggestions will be appreciated.


Solution

  • No, the CSS counter values cannot be accessed outside of CSS. So, there is no way to assign this to a input box or access the value using JS/jQuery etc. More details can be found in the answer here and so I am not going to repeat it.

    Like charlietfl had mentioned in his comment, I would ideally recommend checking with the server and then setting the value (using AJAX) or completely do the serial number generation at the backend and just display placeholder values (like 1, 2, 3 etc) in the page. I say this because (a) uniqueness cannot be fully attained if they are generated at client-side and (b) values could easily be tampered if they are generated at client-side and stored as-is into the DB. Either way, it would also be better to validate the incoming data before storing to DB.

    But, if for whatever reason you wish to proceed doing this at client side, then you could write a simple function jQuery's index() feature and set the index of the tr to the input box. I am not an expert in jQuery and so there are chances that this could be achieved in a simpler way.

    function numberRows(){
      $("#tb2 tr").each(function(){
        $(this).find("td:first-child input").val($("#tb2 tr").index(this));
      });    
    }
    

    Fiddle Demo

    As Brodie had indicated in comments, you may want to change the input from readonly to a hidden input but I'd leave that to you. I used a readonly box just to visibly show the value.