Implementing input verification for a dropdown menu in HTML

I am looking to implement a simple validation check on my HTML form. Specifically, I want an error message to appear next to the dropdown select if the user chooses the "18 - 24" option, stating 'You must be 25+'.

<select class="element select medium" id="element_3" name="element_3"> 
<option value="" selected="selected"></option>
<option value="1" class="error" id="error">18 - 24</option>
<option value="2" >25 - 34</option>
<option value="3" >35 - 44</option>
<option value="4" >45 +</option>

Initially, I tried adding both a class and ID to value 1. Then, I attempted using the following JavaScript code:

function hidestuff(page){
   document.getElementById(error).style.visibility="hidden";
}

function showstuff(error){
   document.getElementById(error).style.visibility="visible";
}

I tried toggling between showing and hiding the error message using JavaScript. My goal was to hide the message when the page loads, and then display it when the error div is toggled. However, this approach did not work as intended. I also included the corresponding CSS. Could someone provide guidance on how to properly implement this functionality?

Answer №1

To create a similar effect, utilizing jQuery can help:

Take a look at this JSFiddle

Using jQuery:

$(document).ready(function() {

    $('#errorMsg').hide();  //making sure the error message is hidden

    $('#element_3').on('change',function() {

        // any option with the class "error" will trigger the display of the error message 
        // (even if a 0-17 option is added in the future)
        // To select an element by ID: $(this).find(":selected").attr('id') == 'error'

        if ($(this).find(":selected").hasClass('error')) {
           $('#errorMsg').show();   
        } else {
            $('#errorMsg').hide();   
        }
    });
});

Accompanied by some HTML:

<select class="element select medium" id="element_3" name="element_3"> 
    <option value="" selected="selected"></option>
    <option value="1" class="error" id="error">18 - 24</option>
    <option value="2" >25 - 34</option>
    <option value="3" >35 - 44</option>
    <option value="4" >45 +</option>
</select>
<div id="errorMsg">You must be over 25</div>

To enhance the appearance, consider adding CSS:

#errorMsg {
    display: inline-block;    
    background-color: #fdd;
    font: 12pt arial;
    color: #f00;

    padding: 2px 5px 2px 5px;
    border: 1px solid #f00;
    border-radius: 5px;
    width: 200px;
}

Answer №2

It appears that the method you are employing is similar to the one outlined below:

<select id="myselect" onchange="check();">
    <option value="0">Choose an option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<div id="error" style="display:none;">Error message</div>
<div id="page" style="width:100px;height:100px;border:1px solid black;display:none;">My page</div>
<script>
    function check() {
        switch (parseInt($('#myselect').val())) {
            case 0:
                $('#error').show();
                $('#page').hide();
                break;
            case 1:
                $('#error').show();
                $('#page').hide();
                break;
            case 2:
                $('#error').hide();
                $('#page').show();
                break;

        }
    }
</script>

http://jsfiddle.net/SS3gc/4/

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

Turn the flipcard hover effect into an onclick action

After successfully creating interactive flip cards using CSS hover effects, I am now faced with the challenge of adapting them for mobile devices. I'm struggling to figure out how to translate my hover effects into onclick events for a mobile-friendl ...

Is it possible to make each letter on a page a different color using JavaScript? I've noticed that there is always an additional set of span tags before each opening tag on the page

Page hosted using Google Drive Within the JS code: var doc_part = false; //denotes if a character is not part of the visible document var page_body; //function to generate random rgb values function randomInt(max, min) { return Math.floor((Math.ran ...

Is it possible to include alligator tags(<% %>) within a JavaScript string?

I am attempting to redirect a page by pulling the url from the config file. However, when I try the following code: <script type="text/javascript"> <%string redirectUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["RedirectU ...

Concealing and revealing template URLs with AngularJS

I am currently working with a dynamic Array in my Controller that contains templates (html files) structured similarly to the example below: $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: ...

The issue of 'require is not defined' arises when using Webpack configuration including "target: 'node'" and "type: 'module'"

My webpack configuration for an express server that utilizes ES6 modules, includes "type": "module" in the package.json file, and has target: 'node' specified, fails with the error ReferenceError: require is not defined. Upon ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

Issue with positioning in Excanvas VML

After struggling through the implementation of excanvas on ie8, I managed to sort out the dynamic element issue. The once hidden elements are now rendering properly throughout most of the app, but just when it seemed like all was going well, another proble ...

Enhancing a section through Ajax using Rails

Having some trouble updating a partial in Rails using Ajax. Basically, I have a Post model with a Karma attribute. Users can vote up or down to adjust the Karma for the post. I want to allow users to update the karma value asynchronously using Ajax, but I ...

When values are deleted from an array object, the entire structure is altered even when browsing through the keys

Manipulating arrays within objects: -----code ------- var obj1 = { 'a': ['a','b','c','d'], 'b':['b','d','r','a']} Object.keys(obj1).forEach(element =& ...

Problem with XRController Raycast Range

Having trouble with raycasting in THREEJS using the XR controller when trying to detect objects beyond a distance of 40 units. Raycasting works perfectly within 40 units. Referenced the example in THREEJS: Any suggestions on how to extend the raycasting ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

How can you stop a document event listener from triggering?

Utilizing document.addEventListener('touchstart', this.onDocument); allows me to recognize when a user taps outside of an element. However, within my button click handler, the following code is present: toggleItemActive(e) { e.stopPropa ...

Issue with VueJS component prop displaying only the last JSON entry when it is reused

My aim is to reuse a vue component with a prop that takes data from a json object. However, the issue I'm facing is that all instances of the component are displaying the same data instead of data based on the index of the json object. This is how my ...

The second function in Vue.js was unable to initialize the data field within data() due to a missing call for assistance

I have very little experience working with vue js. There are two functions that I am using: loadComponentsOfUser() and loadUserId(). The loadComponentsOfUser() function depends on the userID field being loaded by the loadUserId() function. data() { retu ...

Scaling background images in HTML and CSS to perfectly fit any screen size

As I am in the process of creating my portfolio website, I have encountered an issue with the background image not adjusting to the screen size. Currently, I am using HTML and CSS for the design. Can you please provide guidance on how to code the backgro ...

Rotating an object in Three.js along the radius of a sphere

I want to position an object at the end of a sphere's radius based on its coordinates (x, y, z). In traditional mathematical formulas for the coordinates of a point on a sphere, we use: var x = radius * Math.cos(phi) * Math.cos(theta); var y = radiu ...

Determining the width of the parent HTML element based on a child button that includes

I am working with an array containing the number of columns I want to extract. leftPlace = <(number | undefined)[]>[]; In my HTML, there is a button that I click to extract a column: <th class="table-cell"> <div class="tabl ...

mongoose connection to database failed error

I'm facing an issue when trying to connect to a database using mongoose. The problem arises when I execute this code var mongoose = require('mongoose').Mongoose; var db = mongoose.connect('mongodb://localhost/goaljuice'); Upo ...

Choose a value from a dropdown menu in Angular

Currently, I am developing an angularjs application and encountering difficulties setting the selected value in a select tag. Please note that the 2nd option has the selected="selected" I have tried various solutions such as setting the doc type to HTML5 ...

Using React Router (version 4) - navigating backwards in your application

Currently struggling to find a way to navigate back to the previous page using [react-router-v4][1] Here is the setup I have on my initial landing page: <Router> <div> <Link to="/"><div className="routerStyle"><Glyphicon ...