Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page?

Below is a simple form code example:

<form name="searchLocations" method="POST">
        <select name="locationName">
            <?php 
            $sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
            while ($row = mysql_fetch_array($sql)){
            echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
            }
            ?>
        </select>
        <button onclick="loadXMLDoc(indexSearchingSubmit);" id="searchingSubmit">Search</button>
    </form>

The goal is to keep the selected dropdown option stored within the main Ajax coding of the page, ensuring that it remains accessible when interacting with different Ajax elements.

Here's an illustration of the main Ajax logic:

<script>
window.onload = function () {
    var everyone = document.getElementById('everyone'),
        searching = document.getElementById('searching'),
        searchingSubmit = document.getElementById('searchingSubmit');

    everyone.onclick = function() {
        loadXMLDoc('indexEveryone');
        everyone.className = 'filterOptionActive';
        searching.className = 'filterOption';
    }

    searching.onclick = function() {
        loadXMLDoc('indexSearching');        
        searching.className = 'filterOptionActive';
        everyone.className = 'filterOption';
    }

     searchingSubmit.onclick = function() {
        loadXMLDoc('indexSearchingSubmit');  
    }

    function loadXMLDoc(pageName)
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("leftCont").innerHTML=xmlhttp.responseText;
            }
          }

        function get_query(){
          var url = location.href;
          var qs = url.substring(url.indexOf('?') + 1).split('&');
          for(var i = 0, result = {}; i < qs.length; i++){
            qs[i] = qs[i].split('=');
            result[qs[i][0]] = decodeURIComponent(qs[i][1]);
          }
          return result;
        }

        xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
        xmlhttp.send();
        }
}
</script>
<!-- ends ajax script -->

Answer №1

When working with jQuery:
    $('[name="locationName"]').change(function() {
        SELECTED_VALUE = $(this).attr('value');
    });

If not using jQuery:
    Add the onChange attribute to your SELECT element and also include an id.
    Create a JavaScript function as an onchange handler that simply retrieves the selected value and assigns it to SELECTED_VALUE.

<select name="locationName" onChange="setSelected()" id="locationSelect">

function setSelected(){
    var mySelect = document.getElementById("locationSelect");
    SELECTED_VALUE = mySelect.options[mySelect.selectedIndex].value;
}

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

Developing a system mode called "night mode"

I've decided to incorporate a dark mode feature into my Wordpress theme. Creating both dark and light modes was a breeze, but now I want to add a third mode that serves as the default for pages. This new mode will automatically switch between dark a ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

React Tour displays incorrect positions when coupled with Slide transitions in Material UI Dialog

Currently, I am utilizing the react-tour library to incorporate a guidance feature into my project. The issue arises in the initial step which involves a small component within a <Dialog /> that requires highlighting. However, due to a transition ef ...

Performing a count query with MongoDB Mongoose by grouping data based on multiple fields

I've developed an analytics API using MongoDB. Here is the model for my sessions: const sessionSchema = new Schema( { user: { id: Number, name: String, email: String }, }, { timestamps: true }, ); My goal is to calculate the number of uni ...

Sharing AngularJs controllers between different modules can help streamline your

I'm facing an issue with trying to access an array from one controller in another controller. Despite simplifying the code for clarity, I still can't seem to make it work. Here is my first controller: app.controller('mycont1', [' ...

What steps do I need to follow to execute React/Next code that I have downloaded from GitHub?

I recently obtained a zip file from https://github.com/prgrms-web-devcourse/Team_Price_Offer_FE and extracted its contents. When attempting to launch the program in Visual Studio Code, I inputted the command npm start but encountered an issue. Team_Price_ ...

Error occurred during the parsing of an AJAX response

Hello, I am currently exploring the world of JavaScript and jQuery. I recently encountered a situation where I initiated an AJAX call in my code and received an unexpected response. My current challenge revolves around implementing an autocomplete functio ...

Eliminating redundant JSON records upon fetching fresh data

I have a list containing duplicate entries: var myList = [ { "id": 1, name:"John Doe", age:30 }, { "id": 2, name:"Jane Smith", age:25 }, { "id": 3, name:"John Doe", age:30 }, { &qu ...

Retrieve a specific value from a JavaScript object

Utilizing the npm package app-store-scraper, I am extracting the app IDs of 1000 apps from the App Store. My objective is to retrieve the "id" field from each JavaScript object and save it in a .csv file. How can I accomplish this task? Below is the code ...

Gulp is showing an error of "Module Not Found" despite the module being present in the project

I've come across an unexpected issue and I'm at a loss for solutions. As part of my exploration into JS unit testing, I am configuring gulp with Jasmine. However, when I run my gulp build, I encounter the following error: Error: Cannot find modu ...

Storing HTML5 Canvas Data with Ajax in ASP.NET

Having an issue trying to send canvas Data to a web service using Ajax, resulting in the following error: 500 (Internal Server Error) Here is the JavaScript code being used: var imageData = canvas.toDataURL("image/png"); imageData = imageData.replace( ...

Stop a hyperlink from refreshing the webpage

Currently, I am in the process of developing a responsive menu. You can view a demo of my progress on Codepen. In order to prevent the page from reloading when I click a link within the menu, I have implemented the following JavaScript code: $('nav. ...

Ensuring no null objects are present in the jQuery each function

In order to iterate through each key value pair in a JSON element and display it, I am encountering an issue where some of the keys have null values. As a result, using $.each is throwing an error: TypeError: obj is null I do not want to remove the null ...

Fetching data from an AJAX request in Laravel with JavaScript and returning it as

Despite my efforts, I am still struggling to understand this concept. I am having trouble sending a JavaScript variable to the controller along with form data. The form data is being sent successfully, but not the JavaScript variable. JS $('#form&a ...

The Checkboxlist generated by jQuery-Ajax does not function when clicked on

I have a dynamic radio button list (rblCategories) that, when the selected value changes, triggers the creation of a checkbox list using ajax and populates it. However, I am facing an issue with updating my datatable when any checkbox is checked/unchecked ...

Can I securely hand off a JavaScript callback to an FFI function that executes it in a separate thread?

I need to use a C function that takes a callback and executes it on a separate thread: void execute_in_new_thread(void (*callback)()) { // create a new thread and run `callback` in it ... } To accomplish this from JavaScript using Node-FFI, I have to ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

Learn how to toggle the visibility of three div elements arranged horizontally

$(document).ready(function () { $("#toggle").click(function () { if ($(this).data('name') == 'show') { $("#sidebar").animate({ width: '10%' }).hide() $("#map").an ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...