So let's say I have some code that looks like this and I want the form to only be submitted if the sum of x and y is 10 or less. Now when I run this code it completely ignores the "max" and just submits the form. As soon as I remove the "readonly" it does look at the "max". Is there any way to have a max for a readonly element? And if so, how?
<!DOCTYPE html>
<html>
<head>
<title>Max for readonly</title>
</head>
<body>
<script>
var x = 5;
var y = 7;
var sum = x + y;
document.getElementById('demo').value = sum;
</script>
<form>
<input id="demo" type="number" max="10" readonly>
<input type="submit">
</form>
</body>
</html>
Thanks in advance
You can not do this: document.getElementById('demo').value = sum; if at the current moment input with id = 'demo' is readonly.
In your case you're not making an assignment, cuz element is readonly.
That's why the max check doesn't work for you. Since there is no value there.
You can make sum and only than set your input readonly = true;
<!DOCTYPE html>
<html>
<head>
<title>Max for readonly</title>
</head>
<body>
<script>
var x = 5;
var y = 7;
var sum = x + y;
document.getElementById('demo').value = sum;
document.getElementById('demo').readOnly = true;
</script>
<form>
<input id="demo" type="number" max="10">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Max for readonly</title>
</head>
<body>
<form>
<input id="demo" type="number" max="10">
<input type="submit">
</form>
<script>
var x = 5;
var y = 7;
var sum = x + y;
document.getElementById('demo').value = sum;
document.getElementById('demo').readOnly = true;
</script>
</body>
</html>