3.1 Form and Event Handling
3.1 Form and Event Handling
Day 3.2:
Form Controls:
<input> Tag:
The most commonly used form element. The type attribute defines the type of data that the
input will accept.
<button type="submit">Submit</button>
<button type="button" onclick="alert('Button clicked!')">Click Me</button>
● The first button submits a form.
● The second button triggers a JavaScript alert when clicked.
The <input type="text"> element creates a single-line text input field where users can enter text.
<label for="name">Name:</label>
<input type="text" id="name" name="name">
This creates a text field where users can input their name.
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"></textarea>
This creates a text area where users can enter a longer message.
<label for="country">Country:</label>
<select id="country" name="country">
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
</select>
This creates a dropdown menu where users can select their country.
Form Events:
onsubmit Event
<script>
function validateForm() {
const username = document.getElementById("username").value;
if (username === "") {
alert("Username must be filled out");
return false; // Prevent form submission
}
return true; // Allow form submission
}
</script>
Explanation: The form will only submit if the validateForm() function returns true. Otherwise, an
alert is shown, and submission is prevented.
Example :
<html>
<head></head>
<body>
<br><br>
<label>Select Gender : </label><br>
<br><br>
<label>Select Country : </label><br>
<select id="country" name="country">
<option>India</option>
<option>USA</option>
<option>UK</option>
</select>
<br><br>
<label>Upload File : </label><br>
<input type="file" name="file" placeholder="Enter your file" />
<br><br>
<label>Message : </label><br>
<textarea id="message" name="message" rows="5" cols="100"></textarea>
<br><br>
<label><input type="checkbox" name="agree" /> I agree terms and conditions
: </label><br>
<br><br>
<label for="subscribe"><input type="checkbox" id="subscribe"
name="subscribe"> Subscribe to newsletter</label><br>
<br><br>
<input type="submit" name="submit" value="Submit Form"/>
<button type="reset" onclick="alert('Form is reset');">Reset</button>
</form>
</body>
</html>
<script>
function validateForm()
{
</script>