Tamil Nadu HSE Second Year Computer Science study materials
Tamil Nadu HSE Second Year Computer Science study resources

The Quiz Form That Reloads and the CSS Colour Trap

Tamil Nadu HSE Second Year Computer Science · Put your knowledge to work in context.

All case studies

The Quiz Form That Reloads and the CSS Colour Trap

The school's computer science association is creating a web page for an online science quiz. The form has three fields: name, roll number (exactly five digits) and email. A student writes this HTML: <form action="/submit" onsubmit="validate()"> ... <input id="roll" ...> ... </form>. The JavaScript function validate() reads document.getElementById("roll").value, checks whether the length is 5 and whether all characters are digits, and displays an alert if not. However, whenever the roll number is invalid, the alert appears and the page still reloads, losing all entries. The page also has an element with class="highlight" and id="notice". The CSS contains .highlight { color: red; } and #notice { color: blue; }. A student expects the element to be red because the class rule is written first. The association also wants the roll number check to work even if JavaScript is disabled.

1. Explain why the page reloads after the alert and give two JavaScript fixes.

Read the worked answer

The inline handler calls validate() but does not return its result. When a handler returns undefined, the browser performs the form's default submission.

Fixes: (1) change the form to onsubmit="return validate()" and make validate() return false when invalid and true when valid; (2) accept the event parameter and call event.preventDefault() inside the invalid branch. Either stops the reload and preserves the entries.

2. Determine the colour of the element with both class and id and explain using CSS specificity. Then state one way to make the class rule win without changing the HTML.

Read the worked answer

The element is blue. CSS specificity: an ID selector has specificity (1,0,0), while a class selector has (0,1,0). The ID rule wins despite source order.

To make the class rule win without changing HTML, add !important to the class declaration: .highlight { color: red !important; }. A more targeted selector such as #notice.highlight could also win, but that still refers to the ID.

3. The association wants the five-digit roll number rule enforced without JavaScript. Write the relevant HTML attribute and explain how it improves reliability. Also state one limitation.

Read the worked answer

Use pattern="[0-9]{5}" on the roll input, preferably with required and maxlength="5". The browser checks the value against the regular expression before submission, so a non-JavaScript user still gets validation.

Limitation: client-side validation can be bypassed (for example, by disabling validation or sending a direct request), so the server must repeat the check. Older browsers may not support pattern fully.