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

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: I'm curious, how can I implem ...

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

JavaScript Page Search - Error in Finding Single Result

I am currently working on implementing a 'find in page' search box and have come across some JavaScript code that is working really well. Everything works great when there are multiple strings, as pressing enter cycles through the results and the ...

Creating diverse content for various tabs using JavaScript

I have developed a code that uses a for loop to generate tabs based on user input. var tabs = ""; var y = 1; for (var x = 0; x < tabNum; x++) { tabs += "<li class = 'tabbers'>" + "<a href='#tab'>Tab</a>" + "& ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

Leveraging JSON for parsing xmlhttp.responseText to auto-fill input fields

Is there a way to utilize JSON for parsing xmlhttp.responseText in order to populate textboxes? I've been struggling to achieve this using .value and .innerHTML with the dot notation, along with b.first and b.second from the json_encode function in th ...

Search for specific parameters in an array and retrieve them

I have been attempting to sift through an array of data retrieved from my API, but unfortunately, the data remains unfiltered. I suspect that it might be due to the way I implemented my method or perhaps my params are not being returned correctly. Below ar ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...

Reorganize the JSON data to match the specified format

{ "EUR": { "Description": "", "Bid": "1.1222", "Region": "", "Bid1": "1.1283", "CurrencyCode": "EUR", "FeedSource": "1", "Ask": "1.1226", "ProviderName": "TEST 1", "Low": "1.1195", ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Installing v8-profiler on Windows 8 (64 bit) through npm: a step-by-step guide

The v8-profiler module is widely recognized as the go-to tool for identifying memory leaks in node.js applications. However, attempting to install it with npm install v8-profiler results in an error message related to compatibility issues between 32bit an ...

The function "Jest spyOn" does not exist

I’m currently facing an unfamiliar error while testing my React component using Jest. Here’s the code snippet for my <Row/> component: In my Row component, there are various methods like showDetailsPanel(), handleStatusChange(), handleModalCanc ...

Setting up a basic webhook server with Node and Express

I'm struggling to locate comprehensive tutorials on webhooks for beginners. Being new to this concept, I have only come across basic explanations of how they operate. Our current requirement is to inform users of our APIs about new records. With Kafk ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...

Retrieve distinct keys from a JSON file in Node.js

Below is an example of JSON data: [ { "Name": "User1", "primaryRegion": "US" }, { "Name": "user2", "primaryRegion": "US" }, { "Name": &q ...

Tips for avoiding cursor sticking in css rotate transform in firefox?

I have a unique challenge in this code where I want the user to grab the black square and rotate it around the inner circle. Check out the code snippet here. While attempting to rotate the square, you might notice that the cursor sometimes gets stuck in ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

Could someone clarify the specific workings of the Google V8 bytecode related to the creation of object literals

Check out this awesome piece of JavaScript code! const person = { name: 'John', age: 30 }; console.log(person); Here's the Google V8 byte code generated by using node js option --print-bytecode. [generated bytecode for function:] ...