Dular SharmaDular SharmaDular Sharma
(Monday - Saturday)
sharmadular7392@gmail.com
Himatnagar
Dular SharmaDular SharmaDular Sharma

Chapter 17. Forms and Form Values In JavaScript

34 Views

Forms are a crucial part of web applications, enabling users to input and submit data. JavaScript provides powerful tools to interact with forms and their values, allowing for dynamic and responsive user experiences. This blog will explore how to work with forms and form values in JavaScript, focusing on accessing and manipulating various types of form elements.

Accessing Form Elements

To interact with forms and their values, you first need to access the form elements. JavaScript offers several methods to achieve this.

Using getElementById

You can use getElementById to access form elements by their ID.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Example</title>
</head>
<body>
    <form id="myForm">
        <label for="age">Age:</label>
        <input type="number" id="age" name="age">
        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <script>
        function submitForm() {
            let age = document.getElementById('age').value;
            console.log('Age:', age);
        }
    </script>
</body>
</html>

In this example, clicking the “Submit” button logs the value of the age input field to the console.

Working with Different Form Elements

JavaScript allows you to work with various types of form elements, including checkboxes, radio buttons, selects (dropdowns), and textareas.

Checkboxes

You can access and manipulate the state of checkboxes.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox Example</title>
</head>
<body>
    <form id="myForm">
        <label for="subscribe">Subscribe to newsletter:</label>
        <input type="checkbox" id="subscribe" name="subscribe">
        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <script>
        function submitForm() {
            let isSubscribed = document.getElementById('subscribe').checked;
            console.log('Subscribed:', isSubscribed);
        }
    </script>
</body>
</html>

In this example, clicking the “Submit” button logs whether the user has checked the subscription checkbox.

Radio Buttons

You can access and manipulate the selected state of radio buttons.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Radio Button Example</title>
</head>
<body>
    <form id="myForm">
        <label>Gender:</label>
        <input type="radio" id="male" name="gender" value="male">
        <label for="male">Male</label>
        <input type="radio" id="female" name="gender" value="female">
        <label for="female">Female</label>
        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <script>
        function submitForm() {
            let gender = document.querySelector('input[name="gender"]:checked').value;
            console.log('Gender:', gender);
        }
    </script>
</body>
</html>

In this example, clicking the “Submit” button logs the selected gender.

Select (Dropdown)

You can access and manipulate the selected value of a dropdown.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Select Example</title>
</head>
<body>
    <form id="myForm">
        <label for="country">Country:</label>
        <select id="country" name="country">
            <option value="USA">USA</option>
            <option value="Canada">Canada</option>
            <option value="UK">UK</option>
        </select>
        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <script>
        function submitForm() {
            let country = document.getElementById('country').value;
            console.log('Country:', country);
        }
    </script>
</body>
</html>

In this example, clicking the “Submit” button logs the selected country.

Textarea

You can access and manipulate the value of a textarea.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Textarea Example</title>
</head>
<body>
    <form id="myForm">
        <label for="comments">Comments:</label>
        <textarea id="comments" name="comments"></textarea>
        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <script>
        function submitForm() {
            let comments = document.getElementById('comments').value;
            console.log('Comments:', comments);
        }
    </script>
</body>
</html>

In this example, clicking the “Submit” button logs the content of the textarea.

Manipulating Form Values

JavaScript allows you to dynamically manipulate form values based on user interactions or other conditions.

Pre-filling Form Values

You can pre-fill form values using JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pre-fill Form</title>
</head>
<body>
    <form id="myForm">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <button type="button" onclick="preFillForm()">Pre-fill Form</button>
    </form>

    <script>
        function preFillForm() {
            document.getElementById('username').value = 'JohnDoe';
        }
    </script>
</body>
</html>

In this example, clicking the “Pre-fill Form” button sets the value of the username field to “JohnDoe”.

Clearing Form Values

You can clear form values using JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clear Form</title>
</head>
<body>
    <form id="myForm">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        <button type="button" onclick="clearForm()">Clear Form</button>
    </form>

    <script>
        function clearForm() {
            document.getElementById('email').value = '';
        }
    </script>
</body>
</html>

In this example, clicking the “Clear Form” button clears the value of the email field.

Submitting Form Data

You can submit form data using JavaScript, either by manually triggering the form submission or by handling it with AJAX for asynchronous operations.

Submitting Form Data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Form</title>
</head>
<body>
    <form id="myForm" action="/submit" method="POST">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

In this example, submitting the form sends the data to the server using the specified action URL and method.

Submitting Form Data with AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Form with AJAX</title>
</head>
<body>
    <form id="myForm">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <script>
        function submitForm() {
            let username = document.getElementById('username').value;
            let xhr = new XMLHttpRequest();
            xhr.open('POST', '/submit', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log('Response:', xhr.responseText);
                }
            };
            xhr.send('username=' + encodeURIComponent(username));
        }
    </script>
</body>
</html>

In this example, clicking the “Submit” button sends the form data to the server using AJAX, without reloading the page.

Working with forms and form values in JavaScript is essential for creating dynamic and interactive web applications. By mastering the techniques to access, manipulate, and submit form data, you can enhance the user experience and build more responsive applications. Experiment with these methods in your projects to improve your JavaScript skills and create better web applications.

Previous Post
Newer Post

Leave A Comment

Need Help?