Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jquery or PHP.

 <select name= "countrylaw">
         <option value = "1">Afghanistan</option>
         <option value = "2">Albania</option>
         <option value = "3">Algeria</option>
         <option value = "4">Andorra</option>
         <option value = "5">Angola</option>
         <option value = "6">Antigua & Deps</option>
         <option value = "7">Argentina</option>
         <option value = "8">Armenia</option>

Below is my JavaScript code, but it doesn't seem to be working:

        var select1 = document.getElementsByName("country");
        var selected1 = [];
        for (var i = 0; i < select1.length; i++)
        {
         if (select1.options[i].selected) 
            {
                 alert("File Selected for " + select1.options[i].value +" ")

            }
        }

Answer №1

To capture user selection changes, it is recommended to utilize the onchange event in this manner:

var select = document.getElementsByTagName("select")[0];

select.onchange = function(){
    if(select.selectedIndex == -1) return null;   // ensure an option is selected

    // Display the text of the currently selected option
    alert(select.options[select.selectedIndex].text); 
}

DEMO

Your initial test used a for-loop for a single run. To cater to dynamic user selections, implementing an event listener like onchange is essential.

Answer №2

If you want your select box to allow multiple selections, just include the multiple attribute in it.
To execute a javascript function every time the user changes their selection, add the onchange attribute:

<select name="countrylaw" multiple onChange="showSelectedCountry(this)">
         <option value = "1">Afghanistan</option>
         <option value = "2">Albania</option>
         <option value = "3">Algeria</option>
         <option value = "4">Andorra</option>
         <option value = "5">Angola</option>
         <option value = "6">Antigua & Deps</option>
         <option value = "7">Argentina</option>
         <option value = "8">Armenia</option>
</select>

Next, create the callback function:

showSelectedCountry = function(select){
    for(var i = 0; i < select.selectedOptions.length; i++){
        alert(select.selectedOptions[i].innerHTML);
    };
}

You can view the demonstration on jsFiddle.

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

Automatically modify browser configurations to disable document caching

Is it possible to prevent browsers from caching pages using JavaScript? I've noticed that even though PHP has a redirection implemented once the user logs in, when they press the browser's history button, it goes back to the login form. This is b ...

Tips for encoding AngularJS ng-model in real-time

Recently, I embarked on a new project and wanted to incorporate some AngularJS magic. The only obstacle is my limited expertise in AngularJS or JavaScript, making it difficult for me to figure out how to make it work. One key requirement is that the functi ...

Tips for populating an array with information gathered from an axios request within a React application

Currently, I am using axios to fetch data from an API and attempting to store the retrieved data in a variable that represents an array within the state of the component. However, when I try to do so, I encounter the following error: Objects are not valid ...

Instructions for resolving the Sys.ArgumentTypeException error: The object of type 'Object' cannot be converted to type 'Function'

I encountered a specific error in my JavaScript function that I'm struggling to resolve. Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'Function'. Parameter name ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

Generate JSON on-the-fly with ever-changing keys and values

I am new to coding and I'm attempting to generate JSON data from extracting information from HTML input fields. Can anyone guide me on how to create and access JSON data in the format shown below? { Brazilians**{ John**{ old: 18 } ...

Employing jQuery Mobile with MVC3 for seamless auto-submit functionality

When I remove jQuery Mobile, the code works perfectly! The form: @using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" })) { @Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town") } The Javascript: & ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

socket.io initialization and finalization events

Currently, I am integrating socket.io with express 3 for my application development. I am interested in implementing loader animations that will appear when a message is incoming and disappear once the message has been received. Similar to how jQuery&apos ...

Struggling with the loading of intricate attribute data into an array of arrays

I am struggling with loading different data attributes into an array of arrays. I have managed to load single data attributes into the dataArray, but when it comes to the data-size which contains groups of arrays in string format, I am facing difficulties ...

"Creating a function within a knockout viewmodel that is populated with JSON data: A step-by-step guide

Struggling with defining a function inside my viewmodel. I retrieve json data using jquery getJSON and then map it to the viewmodel. $.getJSON('/Company/GetCompanies', function(data) { var viewModel = new CompanyViewModel() viewModel.m ...

Disable the time selection feature in the text input field

Despite seeing the same question asked before for this issue, I am looking for a solution that does not involve replacing the textbox with the same ID. When Timepicker is selected in the dropdown menu timepicker, it should activate in the textbox (which i ...

Utilizing jQuery to select an attribute containing a special character

There is a special div with a unique data-id: <div data-id=""> </div> I tried to target this div using jQuery, but it didn't work as expected: jQuery("[data-id='']").text('hello'); Can anyone help me on how to ...

Attempting to showcase a collection of values, specifically focusing on highlighting the even numbers within the array

const sampleArray = [ 469, " " + 755, " " + 244, " " + 245, " " + 758, " " + 450, " " + 302, " " + 20, " " + 712, " " + 71, " " + 456, ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

Symfony is unable to access uploaded files from an AngularJS interface

For the past 3 days, I've been grappling with uploading files via AJAX to my Symfony2 application using AngularJS. I'm utilizing my Symfony app as an API to deliver data to my Angular front end. While I can successfully post text and other data, ...

Error: Unable to perform 'getComputedStyle' on the 'Window' object: the first parameter must be of type 'Element'

My goal is to create a rotating effect with a center circle containing 5 inner divs. When the device is rotated on the gamma axis, I want the circle div to rotate in accordance with the gamma degree, while the inner divs rotate in the opposite direction to ...

Updating the color of text when clicking on a link using javascript

I am facing an issue where I cannot seem to change the text color using JavaScript. The functionality to show and hide div tags is working perfectly, but changing the color seems to be a challenge. It's worth noting that there are no styles defined fo ...

MVC4: Exploring the Strategy for Handling Nested Ajax Requests

Creating a form in a web application, I implemented filtering data based on user selection using AJAX to retrieve JSON nested data from BankPlans table. However, I encountered an issue when attempting to fetch all required documents for each bankID from an ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...