Checking the list box and radio button using JavaScript based on their respective IDs

Looking to validate the selection of a listbox and radio button using their respective IDs when a submit action occurs. When testing in the browser, no alert is being displayed. The goal is to trigger the script upon clicking the submit button to verify if a radio button and listbox are selected. If one is selected, do nothing. If none are selected, display an alert message.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">

        function validate()
    {
        if (document.getElementById("drop1").value == "-1")
        {
            alert("please select A");
        }
        if (document.getElementById("drop2").value == "-1")
        {
            alert("please select B");
        }
        if (document.getElementById("drop3").value == "-1")
        {
            alert("please select C");
        }
        if (document.getElementById("drop4").value == "-1")
        {
            alert("please select D");
        }
        if (document.getElementById("drop5").value == "-1")
        {
            alert("please select E");
        }

            var radios = document.getElementsByName("A");
            var formValid = false;

            var i = 0;
            while (!formValid && i < radios.length) 
            {
                if (radios[i].checked) formValid = true;
                i++;        
            }

            if (!formValid) alert("Must check some option!");
            return formValid;
        }

    }
</script>
</head>
<body>
A:<select id="drop1">

    <option value="1">item 1</option>

    <option value="2">item 2</option>

    <option value="3">item 3</option>

    <option value="4">item 4</option>

    <option value="0">All</option>

</select>
 B:   <select id="drop2" >

    <option value="1">item 1</option>

    <option value="2">item 2</option>

    <option value="3">item 3</option>

    <option value="4">item 4</option>

    <option value="0">All</option>

</select>

C:<select id="drop3" >

    <option value="1">item 1</option>

    <option value="2">item 2</option>

    <option value="3">item 3</option>

    <option value="4">item 4</option>

    <option value="0">All</option>

</select>

D:<select id="drop4" >

    <option value="1">item 1</option>

    <option value="2">item 2</option>

    <option value="3">item 3</option>

    <option value="4">item 4</option>

    <option value="0">All</option>

</select>

E:<select id="drop5" >

    <option value="1">item 1</option>

    <option value="2">item 2</option>

    <option value="3">item 3</option>

    <option value="4">item 4</option>

    <option value="0">All</option>

</select>
<input type="radio" id=myradio1 name="A" value="1">one
<input type="radio" id=myradio2 name="A" value="2">two
<input type="radio" id=myradio3 name="A" value="3">three
<input type="submit" value="submit" onclick="validate()">
</body>
</html>

Answer №1

It is important to note that the <code>onsubmit
property is not applicable to an input type, but rather should be used on the <form> element:

<form method="POST"  onsubmit="validate()">


</form>

Make sure to encapsulate your code within the <form> tags.

Check out this jsFiddle link for a demonstration.


If you prefer not to use a <form>, consider using the onclick event instead of onsubmit:

<input type="submit" value="submit" onclick="validate()"/>

Here's a jsFiddle showcasing this alternative approach.


To validate if a select box has been chosen, you can utilize the following code snippet:

if (document.getElementById("drop1").value == "")
{
   alert("Please select option A");
}

Remember to include a 'placeholder' in your select box without a value. This allows the default selection to be the placeholder with no value when nothing else is selected.

When the user selects the placeholder, an error will be triggered.

HTML:

 Option A:<select id="drop1">
    <option value="" style="display: none;">Placeholder</option>
    <option value="2">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
    <option value="4">Item 4</option>
    <option value="0">All</option>
</select>

Take a look at this jsFiddle example for more insight.

This code snippet demonstrates checking one listbox, and similar validation can be applied to others as well.


Ensure to enclose ID names in quotes:

 <input type="radio" id='myradio1' name="A" value="1"/>One
 <input type="radio" id='myradio2' name="A" value="2"/>Two
 <input type="radio" id='myradio3' name="A" value="3"/>Three
 <input type="submit" value="Submit"/>

I hope you found this information helpful!

Answer №2

If you want to retrieve the selected value from a specific dropdown menu, here's how you can do it:

http://jsfiddle.net/qPz8R/

<select id="selectedItem">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="0">All Options</option>

$("#checkSelection").click(function() {
alert($("#selectedItem").val());

});

This script will display an alert with the selected value from the dropdown menu when the user clicks the button.

Answer №3

onsubmit Event is specifically designed to be placed on a form element. However, if you want to set an event for the input element, you can use the onclick event instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing Pop-Ups when browsing on Internet Explorer

I've been working on an Excel VBA macro that automates several tasks on the Medicare website. The macro opens IE, logs in, compares claims, and alerts me to any differences found. However, I've encountered a problem during the log-in step, specif ...

Experimenting with d3 using Node.js, JSDOM, and Jasmine

I am new to Javascript and node.js, and I want to test if a basic bar chart is being rendered in my node.js/d3 application using jasmine. Could someone provide guidance on what steps I need to take? test.js (file that needs testing): var d3 = require(&ap ...

The function is not triggered when the select tag is changed

I'm currently working on implementing a drop-down menu using the <select> element in HTML. Here is the code snippet I have so far: <select id="Parameter1" onchange="function1()"> <option value = "0105" name = "Frequency">Frequency ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

Troubles encountered with switching npm registry

In my Vue 2.7 project with vuetify, I initially installed dependencies using a custom local npm registry, acting as a proxy to the default npm. As the project has expanded, I've started using git actions to deploy to a development server, with varying ...

Horizontal navigation bar encroaching on slideshow graphics

I'm encountering difficulties aligning the horizontal menu below the image slider. When I have just an image without the slider, the menu aligns properly (vertically), but as soon as I introduce the code for the slider, the menu moves to the top and d ...

Understanding the useQuasar() function in Pinia store file with VueJS

I've encountered an issue in my VueJS + Quasar project where I'm trying to utilize useQuasar() in my store file gallery.js, but it keeps returning undefined. A similar problem arose when I was attempting to access useRouter(), however, I managed ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

Creating multiple routes within a single component in Angular without triggering unnecessary redraws

Within the ChildComponent, there is a reactive form that allows for data entry. Upon saving the filled form, the route should be updated by appending an id to the current route. Currently, when saving, the component renders twice and causes screen flicke ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

What might be causing the 500 internal error in jquery.min?

Hello, I am encountering a 500 internal server error when I click this button that performs the following action: $(".btn-email").on('click', function() { swal('Waiting','Please wait, sending email now','info'); ...

Encountering an issue when passing a response using coverage.js

I am utilizing coverage.js to showcase data. When I pass my variable containing the coverage response into an HTML file, similar to how it's done in Angular to display expressions, I encounter a syntax error: <div class="container" style="margin- ...

"Enhance your database by incorporating HTML link clicks through AJAX integration with PHP and MySQL

After browsing through similar questions and attempting to implement it on my website, I'm facing an issue where the expected functionality is not working as intended. When users click on a link, there is no response in the console, and the database r ...

Transform the appearance of several elements using querySelectorAll

When targeting class names in an HTML page with a checkbox using querySelectorAll, keep in mind that getElementByID only works with the first element. QuerySelectorAll displays a nodeList which might require some corrections - how can this be achieved? le ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

When using Laravel with jQuery Ajax, the search for the file address is unsuccessful

Learning Laravel has been a challenging journey for me. I've encountered numerous problems that have made it feel like more of a hindrance than a helpful tool. But the real story lies elsewhere. Working with Laravel 4 and jQuery 2, I attempted to fet ...

Is the spread operator in React failing to function as anticipated?

In my current project, I encountered an issue while trying to pass a GeolocationCoordinates object to a child component using the spread operator. Strangely, in the child props, it appears as an empty object: interface HUDState { geoCoords: Geolocation ...

Learn the best practices for sharing .env values from the main project component to various reusable npm installed components

In recent projects I've worked on using React and Vue.js, I have utilized .env variables to store API URLs for micro services and other configuration settings that are used throughout the root project. However, when it comes to child components insta ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

Sharing stickers with Discord.js version 13

I have encountered an issue while trying to forward messages sent to my bot via DM. Everything is functioning smoothly, except for sending stickers. Whenever I attempt to send a message with a sticker, an Error DiscordAPIError: Cannot use this sticker is ...