I want to set a max length to a field which is inside a table cell. How can I set a max length of 10 digits?
<th width="10%;" style="text-align:center;vertical-align:middle;background-color:black;font-size: 5px;border-left:1px solid #000000";>Testing</th>
Thanks
CodePudding user response:
One solution would be to use javascript by using the function substring()
. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/substring
const ths = document.querySelectorAll('th');
ths.forEach(th => {
const str = th.innerHTML;
th.innerHTML = str.substring(0, 10);
})
th {
text-align: center;
vertical-align: middle;
background-color: black;
font-size: 15px;
border-left: 1px solid #000000;
color: white;
}
<table>
<thead>
<tr>
<th >0123456789abc</th>
</tr>
</thead>
</table>
CodePudding user response:
If you actually are not using an <input>
as the title of the question explicitly says, then the answer is entirely different, and it requires further details from your question.
Having said that, Wimanicesir (see comments on question) is correct, the font must be evenly spread. maxlength
attribute isn't completely effective due to font having variable character widths. A monospace font and some CSS is the best option if you don't want to use JavaScript.
<input>
in a <th>
is unusual but valid. The example below is a complete <table>
because you have to style the entire <table>
to get reliable results. Each style added causes ripples and each element depends upon it's parent element heavily. Comments concerning the question is commented in the example. No details are commented in regards to the <table>
, that would require an answer to a new question.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
/* Setting font-size on <html> becomes default for the entire page */
html {
/* ch units are relative to the width of a zero (ex "0") character which is the
closest to uniform characters you can get in monospace fonts */
font: 2ch/1.25 'Segoe UI';
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
th {
width: 25%;
}
th,
td {
padding: 5px 10px;
border-left: 1px solid #fff;
color: #fff;
background-color: black;
}
input {
/* Needed to set a width -- default inline cannot accept width settings */
display: inline-block;
/* This width is exactly 11ch */
width: 5.5rem;
/* inputs must explicitly inherit font properties */
font: inherit;
/* Change to a monospace font, serif and sans-serif have too many variable lengths
*/
font-family: Consolas;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th><input value='1234567890'></th>
<th>Standard Header</th>
<th>Standard Header</th>
<th>Standard Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</tbody>
</table>
<script></script>
</body>
</html>