Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop down menu with the names of institutions. Here's what the HTML code looks like:

<label for="typeHighInst">Type of institution: </label>
          <select data-dojo-type="dijit/form/FilteringSelect" data-dojo-id="typeHighInst" id="typeHighInst" name="typeHighInst" onChange="getInstitution(this.value)">
            <option value="" selected='selected'>-- select institution type -- </option>
            <?php foreach($InstitutionType as $institutiontype): ?>
            <option value="<?php echo $institutiontype['TypeID']; ?>"><?php echo $institutiontype['Description'];  ?>
            </option>
            <?php endforeach; ?>
          </select>
<label for="nameHighInst">Name of institution: </label>
          <select data-dojo-type="dijit/form/Select" data-dojo-id="nameHighInst" id="nameHighInst" name="nameHighInst">
            <option value="" selected='selected'>-- select institution --</option>
          </select>

The JavaScript function responsible for populating the second drop down menu looks like this:

function getInstitution(str)
{
  var xmlhttp;

if (str=="")
{
    document.getElementById("nameHighInst").innerHTML="<option value='' selected='selected'>-- select institution --</option>";
    return;
}
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)
    {
    //alert(xmlhttp.responseText);
    document.getElementById("nameHighInst").innerHTML=xmlhttp.responseText;
    }
}

  xmlhttp.open("GET","includes/getInstitution.php?typeHighInst="+str,true);
  xmlhttp.send();
}

The issue I'm facing is that when a user selects an option from the first drop down menu (e.g. University), the second drop down menu remains empty instead of displaying a list of universities retrieved via AJAX.

Interestingly, when I switch to using the native select element for the second drop down menu, everything works as expected (the list of universities is displayed correctly).

My question is why does it work with the native select element but not with the dijit/form/FilteringSelect widget? As a newcomer to Dojo, I would appreciate any insights or guidance on how to resolve this issue. Although the native select functionality works, I am keen on utilizing Dojo widgets moving forward.

Thank you in advance for your help.

Answer №1

You can utilize the power of the dojo object to efficiently manipulate lists:

  var dojo_obj = dijit.byId("nameHighInst");
  dojo_obj.attr("innerHTML",xmlhttp.responseText);

Instead of directly accessing elements like this:

  document.getElementById("nameHighInst").innerHTML=xmlhttp.responseText;

If what you're aiming for is this:

  var dojo_obj = dijit.byId("nameHighInst");
  dojo_obj.attr("options",xmlhttp.responseText);

The xmlhttp.responseText for options needs to be structured in a JSON format like this:

options: [
  { label: 'NY', value: 'New York' },
  { label: 'TX', value: 'Texas', selected: true },
  { label: 'AZ', value: 'Arizona' },
  { label: 'CO', value: 'Colorado' },
  { label: 'OR', value: 'Oregon' }
]

Take a look at an example here:

Apply the same approach when retrieving values from a dojo object:

  var dojo_obj = dijit.byId("nameHighInst");
  var val = dojo_obj.attr("value");
  var html = dojo_obj.attr("innerHTML");
  var options = dojo_obj.attr("options");

Answer №2

There are several methods to achieve this goal

Initially, Dojo will parse your HTML content upon loading, and any modifications made to the inner HTML of Dijit elements will not be visible unless manually parsed.

If you choose to change options using HTML, you must call

dojo.parser.parse("id of the enclosing div");

Alternatively,

Utilize dojo.attr to

retrieve options in JSON format from your AJAX response.

var option = [{
    label: 'TN',
    value: 'Tennessee'
},
{
    label: 'VA',
    value: 'Virginia',
}]

selectObj = dijit.byId("id of the element");
selectObj.attr("options",option);

Or,

Directly set the options' values using JavaScript instead of the .attr function, followed by restarting the component.

selectObj.options = option; //JSON object
selectObj.restart();

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

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

Shapes in Three.js with multiple colors

As a newcomer to Three.js and webGL programming, I have successfully created a cone and a cylinder in my scene using the script provided below: var scene; var camera; var renderer; var createACone = function() { // Cone creation code here } var creat ...

The call to Contentful's getAsset function resulted in an undefined value being

I am facing a challenge while trying to fetch an asset, specifically an image, from Contentful and display it in my Angular application. Despite seeing the images in the Network log, I keep encountering an issue where the console.log outputs undefined. Any ...

Utilizing Ajax to dynamically populate table columns

I have an HTML table with specific labels and styles. I am looking for a way to update the table by using the unique 'id' of each row/element and populate the data using Ajax. Can anyone provide a solution or suggestion? <table border="0" ...

On mobile devices, the height of the absolutely positioned element is larger than its

I currently have an element with a background image that includes an absolutely positioned element at the bottom. As the screen width decreases, the height of the absolutely positioned element increases and surpasses the parent element. Since absolutely p ...

Resolving the challenge of Ajax binding in the Telerik ASP.net MVC Grid

I reviewed the codes using Telerik sample, and found that everything is identical except for the model. However, I am unable to view the records in the Grid. // Controller public ActionResult Index() { return View(); } [GridActio ...

What steps should I take to fix the error I'm encountering with React Material UI

import { AppBar, Toolbar, Typography } from '@material-ui/core' import React from 'react' import { makeStyles } from '@material-ui/styles'; const drawerWidth = 240; const useStyles = makeStyles((theme) => { return { ...

Counting records in a nested ng-repeat using AngularJS

As a newcomer to AngularJS, I am facing an issue with a nested ng-repeat using a custom filter. I want to display the record count of Orders being shown, but when applying a product filter, it does not work as expected. For instance, if an order has no pro ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

React-Select is experiencing issues when the options are missing labels or values

I am encountering an issue with react-select as it is not functioning properly for me. The options I am fetching from an API do not include the required value and label properties. Is there a way to work around this using my existing JSON Array? const awar ...

Error in Node.js: Trying to access property 'get' of an undefined object

Although I have some knowledge of JavaScript, I am new to Node.js. Despite it being a common issue, I am having trouble identifying the source of the error because my debugging skills in Node.js are lacking. Here is my app.js: var index = require('. ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...

Using a parameter as a key index in JavaScript

Here's the structure of my Object festivals: Object {friday: Object} friday: Object amazon: Object band: Object Next, I've created a function called`newAct`: function newAct(band, date, startTime, endTime, stage){ var ...

Exploring the power of async/await in combination with map or foreach

I am facing a challenge in retrieving multiple product prices from my database. I had initially thought of using the map or forEach methods to iterate through them and add up the prices to a variable as shown below: // Get Total exports.getTotal = (req,re ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...