How to implement form multiple selection function in JavaScript?
Forms are common elements in web pages and are used to collect user input information. In forms, we often need to provide multiple selection options, such as checkboxes or multi-select lists. JavaScript is a programming language used to add interactive functions to web pages. It can be used to implement multiple selection functions in forms.
Before we begin, let’s first understand what are the common elements of form multiple selection.
Here are some specific code examples showing how to use JavaScript to implement form multiple selection functionality:
<input type="checkbox" id="option1" value="Option 1"> Option 1 <input type="checkbox" id="option2" value="Option 2"> Option 2 <script> const option1 = document.getElementById('option1'); const option2 = document.getElementById('option2'); option1.addEventListener('change', () => { if (option1.checked) { console.log('Option 1 is checked'); } else { console.log('Option 1 is not checked'); } }); option2.addEventListener('change', () => { if (option2.checked) { console.log('Option 2 is checked'); } else { console.log('Option 2 is not checked'); } }); </script>
<input type="radio" id="option1" name="options" value="Option 1"> Option 1 <input type="radio" id="option2" name="options" value="Option 2"> Option 2 <script> const option1 = document.getElementById('option1'); const option2 = document.getElementById('option2'); option1.addEventListener('change', () => { if (option1.checked) { console.log('Option 1 is selected'); } }); option2.addEventListener('change', () => { if (option2.checked) { console.log('Option 2 is selected'); } }); </script>
<select id="options"> <option value="Option 1">Option 1</option> <option value="Option 2">Option 2</option> </select> <script> const options = document.getElementById('options'); options.addEventListener('change', () => { const selectedOption = options.value; console.log('Selected option:', selectedOption); }); </script>
Through the above code example, we You can see how you can use JavaScript to get the status of a user-selected multi-select element and process it accordingly.
To sum up, JavaScript can easily implement the form multiple selection function. By listening to the change event of the element, we can obtain the options selected by the user and perform corresponding operations. The above are just some simple examples, actual applications may require more complex logic and interactive functions. But hopefully these examples will help you understand how to use JavaScript to implement multiple selection functionality in a form.
The above is the detailed content of How to implement form multiple selection function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!