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

Is there ample documentation available for Asp.Net Ajax controls?

Struggling to locate the client side functionality of Asp.net Ajax controls such as calendarextender. How can I determine the specific client side functionalities of each control or Calendar control? So far, I have only discovered the properties ._selected ...

Adding the object's key to an array in JavaScript: A step-by-step guide

Among the objects in my possession are: robot { id skill currentWorkPlace } warehouse { aiStaff currentStatus boxes } I am tasked with creating a function that will add the id of a new worker to the aiStaff array and assign a reference to the ...

Using getStaticProps in Next.js to retrieve menu data and seamlessly integrate it into the layout

I have integrated Sanity.io as a backend for my project, specifically managing the data for my main menu in parent/children object arrays. While I am able to successfully fetch this data, I prefer to utilize getStaticProps to ensure that my site remains c ...

Exploring the Structure of Trees using JavaScript

Here are my terms: var terms = [ { id: 1, name: "Name 1", parent: null }, { id: 2, name: "Name 2", parent: 6 }, { id: 3, name: "Name 3", parent: null }, { id: 4, name: "Name 4", parent: 2}, { id: 5, name: "Name 5", ...

Is the div empty? Maybe jQuery knows the answer

I currently have a <div id="slideshow"> element on my website. This div is fully populated in the index.php file, but empty in all other pages (since it's a Joomla module). When the div is full, everything works fine. However, when it's emp ...

Having trouble extracting a value from a JSON object in JavaScript

I am encountering an issue while attempting to extract a specific value nested within a JSON object. The API call response is provided below. var responseData = { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":n ...

Manage the number of choices available on a drop-down selection form

I am working with a PHP variable $a of an integer type. Based on the value assigned to $a, I want certain options to be visible in a form. For example, if $a=1; then only the first two options should be displayed, and if $a=2; then the first three option ...

How can you pass an authorization token in a Next.js post request when using Django REST framework?

Is there a way to successfully pass a Django authorization token in Next.js using Axios? I attempted this method, but encountered a 404 error. let token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers ...

Suggestions for updating ng-repeat variable with autocomplete functionality?

Many thanks to the Stack Overflow community for helping me resolve my previous angularjs and autocomplete issue. Here is the link to the question: Angularjs with jquery auto complete not working However, I am facing a similar problem now within the ng-rep ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

Can you explain the distinction between the "DOMContent event" and the "load event"?

Within Chrome's Developer tool, there is a blue vertical line marked "DOMContent event fired", as well as a red line labeled "load event fired". Is it safe to assume that the "DOMContent event fired" signifies the initiation of inline JavaScript execu ...

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

Is there a way to determine if a Dojo dialog has been successfully loaded on the page?

I have a function that needs to close a Dojo dialog if it is currently open. How can I determine if a dojo dialog is active? Should I rely on pure JavaScript and check for its existence by ID? if (dijit.byId("blah") !== undefined) { destroyRecursive ...

What is the best way to add a title to a label using jQuery AJAX?

How can I display a title for the label on mouse enter and retrieve the title text using an ajax method? Here is my HTML code: <div id="class"> <label id="cost">@Html.DisplayFor(modelItem => item.PriceId)</label> </div> Be ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...

Creating a Selectable Child Form in ReactJS that Sends Data to Parent Form

Sorry for the lack of details, I'm struggling to explain this situation clearly. I'm currently learning ReactJS and JS. In a project I am working on, I have the following requirements: There is a form where users can input text and numbers. The ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

The clear icon in React will only appear when there is a value inputted

Is there a way to implement the clear X icon that only appears when typing in the input field using reactjs, similar to the search input on the Google homepage? Check it out here: https://www.google.com import { XIcon } from '@heroicons/react/solid&ap ...

Combining the power of Ajax with JSP to enhance your

Is there a way to capture the responseXML that I have generated in my JSP files? Once captured, I plan to transform it into HTML format. Although using a framework or library like jQuery may be easier, I chose to implement it with AJAX. I am encountering ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...