Looping through a dropdown list to pass its items into an iframe

I need help passing dropdown list items to an iframe source (src) through a loop. The issue I'm facing is that the loop runs so fast that it directly goes to the last index of the dropdown list, causing the iframe to load only the last index item of the dropdown. I've tried using both setTimeout and setInterval but it's not working.

Here is my code...
//Dropdown list
<label>Faculty (Employee Code)</label>
        <select class="form-control" name="faculties" id="faculties" onchange="update_chart(this.value,document.getElementById('myIframe'))">
            <option>--Select--</option>
        </select>

//frame
<iframe id="myIframe" src="chart_course_wise.php" frameborder="0" ></iframe>

<script>

function update_chart(str, myIframe) {
        var dept = document.getElementById('dept_code').value;
        var sem = document.getElementById('sem').value;
        var regExp = /\(([^)]+)\)/;
        var emp_code = regExp.exec(str);
        myIframe.src = "chart_course_wise.php?fac=" + emp_code[1] + "&dept=" + dept + "&sem=" + sem;
    }


    function generate(){
        var element = document.getElementById('faculties'),i;
        var length = element.options.length;

        for(i=1;i<length;i++){
           var ddl = element.options[i].value;
           update_chart(ddl,document.getElementById('myIframe'));
        }
    }

</script>

Answer №1

From my understanding, the generate function is being called from a location outside of this snippet.

If you convert your generate() to a JavaScript generator function*, and attach it to the onload event of the frame, you may achieve your desired outcome:

function update_chart(str, myIframe) {
    var dept = document.getElementById('dept_code').value;
    var sem = document.getElementById('sem').value;
    var regExp = /\(([^)]+)\)/;
    var emp_code = regExp.exec(str);
    myIframe.src = "chart_course_wise.php?fac=" + emp_code[1] + "&dept=" + dept + "&sem=" + sem;
    myIframe.document.body.onload = gen.next
}

function* generator() {
    var element = document.getElementById('faculties'),
        i;
    var length = element.options.length;

    for (i = 1; i < length; i++) {
        var ddl = element.options[i].value;
        yield update_chart(ddl, document.getElementById('myIframe'));
    }
}

var gen = generator();
gen.next(); // this is how you execute the generator

Now the generator can be started, which will continue running until encountering the first yield statement. After that, it will pause until the myIframe onload event occurs, triggering gen.next() and allowing the generator to resume execution in a loop.

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

Using the "this" keyword in JavaScript to access the "rel"

Take a look at the JSFIDDLE , where you will notice that the rel attribute in the alert is shown as 'undefined' : var ItemTypeArray = $('input[name^=ItemType]:checked').map(function(){ alert(this.id + ' , r= ' + this.rel) ...

I need to update my database by sending requests to my API, as the changes are not being reflected in the current database state. I am eager to see the

Struggling to grasp the concept of making requests to an API that uses express for CRUD operations. In the code snippet below, .get(/bears) displays a form and in app.post('/bears'), I'm using the 'request' module to send a request ...

Setting up a straightforward static server using node.js

var express = require('express'); var app = express(); app.use('/', express.static('./')); app.listen(80); Error message encountered when running "node server.js" in the CLI: events.js:160 throw er; // Unhandled ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Employing angular-ui-bootstrap to display pop-up notifications

I am new to using Angular and TypeScript and I am attempting to create a popup when an image is clicked. I came across a post on Stack Overflow that provides a solution using IMODALSERVICE. How to utilize angular-ui-bootstrap modals with TypeScript? Howe ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...

Maya model being loaded using Three.js

I've been following a tutorial on how to load Maya models using Three.js, which you can find here. Everything is going smoothly, but the tutorial only covers loading models with a single texture. Below is the source code snippet from the tutorial: ...

What are the steps for reordering an array in MongoDB?

Is there a way to increase or decrease the position of an element within an array stored in a MongoDB object? I explored the <update> API in the MongoDB API, but couldn't find a direct method for this task. I am attempting to use findOneAndUpd ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

Integrating Query String Parameters into GridView Item Templates

Within my gridview, I have a hyperlink located in the first column. When this hyperlink is clicked, the user is directed to Vendor.aspx. I now need to pass the consumer ID (from the clicked row) as a query string to Vendor.aspx. What is the most effective ...

The execution of the Ajax success call is failing to take place

Looking at my recent AJAX call, I realized there might be an issue with how I'm sending the parameters. $.ajax({ type: "POST", url: "Default.aspx/GeneratePdfs", data: '{frequency: "' + $('#ddlReportFrequenc ...

The value of the cookie is not set (version 2.0.6 of react-cookie)

I am encountering an issue with implementing react cookies version 2. I am using webpack-dev-server for testing. Below is the console log: Warning: Failed context type: The context cookies is marked as required in withCookies(App), but its value is unde ...

Updating REST API: Sending a PUT request without requiring all data to be included in json format

I have a controller set up for updating user data. The controller can accept up to 4 values. I am wondering if it is possible to only update the name field when sending data to this route, leaving the rest of the fields unchanged (and not empty). Should ...

Is there a way to deactivate the onClick event when the dropdown placeholder is chosen?

I have experimented with different methods to prevent the onClick event when selecting either placeholder, but I have not been successful. Here is my current code: <div class="choosesign"> <div class="zodiacs"> < ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Preserving the dimensions of an expandable div

Is there a way for a div to maintain its print layout while still allowing for zooming? I attempted to enable zoom functionality on a div using jQuery to adjust the height and width percentages of a specific div with the ID "page". <div style=" heigh ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

Display the appropriate selection choices based on the knockout condition

In my HTML page, there is a dropdown with certain conditions that determine which options should be rendered in the select element. My attempt at achieving this: <select> <!-- ko if: condition() --> <option value="1">1& ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...