Unable to retrieve dropdown value using JavaScript and display it in a div

javaScript code: Retrieving data from a dropdown and displaying it in the inner HTML of a div.

  function showcost() {
        var days = document.getElementById("Ddays");
        var Dudays = days.options[days.selectedIndex].text;
        var div = document.getElementById('cost');
        div.innerHTML = div.innerHTML + Dudays * 1200;
    }

Dropdown code: calling the function showcost() when clicked.

<select class="form-control" name="Ddays" id="Ddays" onchange="showcost()">
               <?php $max_days = $HospitalPack->treat_duration + $HospitalPack->recovery_duration;  ?>
                        @for($i = $HospitalPack->treat_duration; $i<=$max_days; $i++)
                         @if($i == $HospitalPack->treat_duration)
                           <option selected="selected" value="{{$i}}{{'Days'}}" >{{$i}}{{' Days'}}</option>
                         @else
                           <option value="{{$i}}{{'Days'}}" >{{$i}}{{' Days'}}</option>
                         @endif
                        @endfor
                </select>

div code: displaying calculated values after processing data.

<div class="huge" id="cost">{{$HospitalPack->treat_duration * 1200 + $HospitalPack->treat_cost}}</div> 

The above code doesn't seem to be working as expected. I'm having trouble finding the mistake.

Answer №1

Initially, the 'no.selectedIndex' portion is unnecessary and should be removed by eliminating the 'no.'. Perhaps you intended it to be done this way?

var Dudays = days.options[days.selectedIndex].text;

In addition, when the select element is clicked, the browser triggers 'onclick'. For updating the view after selecting a new option, it is recommended to use 'onchange' instead. I would suggest displaying the DOM structure excluding any PHP codes.

Answer №2

Here is the javaScript code snippet:

function displayTotalCost() {
        var daysElem = document.getElementById("Ddays");
        var selectedDaysText = daysElem.options[daysElem.selectedIndex].text;
        var position = selectedDaysText.indexOf("Days");
        var daysNumber = selectedDaysText.slice(0,position-1);
        var costDiv = document.getElementById('Dcost');
        var treatmentCost = <?php echo $HospitalPack->treat_cost ?>;
        costDiv.innerHTML = treatmentCost + daysNumber * 1200;
    }

The dropdown selection code looks like this:

<select class="form-control" name="Ddays" id="Ddays" onchange="displayTotalCost()">
    <?php $maxDays = $HospitalPack->treat_duration + $HospitalPack->recovery_duration;  ?>
    @for($i = $HospitalPack->treat_duration; $i<=$maxDays; $i++)
    @if($i == $HospitalPack->treat_duration)
  <option selected="selected" value="{{$i}}{{'Days'}}" >{{$i}}{{' Days'}}</option>
  @else
<option value="{{$i}}{{'Days'}}" >{{$i}}{{' Days'}}</option>
 @endif
  @endfor

This is the code for the div element:

<div class="huge" id="Dcost">{{$HospitalPack->treat_duration * 1500 + $HospitalPack->treat_cost}}</div> 

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

The links are displaying on separate lines instead of being inline

There is a tags section on the blog detail page. The html code for it is as follows: <td class="tags"> <a href="">tag1></a>, <a href="">tag2</a> </td> However, the tags are appearing on separate lines instead of in ...

Utilizing electron and Systemjs to import node modules

Is it feasible for systemjs to utilize require("remote").require("nodemodule") when the module cannot be located in its registry? A similar mechanism seems to be functioning when utilizing electron with typescript and commonjs modules... Has anyone succe ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

NodeJs is facing a challenge with the global variable for retrieving all routes methods after successful sign in

I have created a blog page with options for signing up and signing in. I used the req.locals.<name> method Using the GET method. Code snippet from server.js app.get('*',(req,res, next) => { res.locals.user = req.user || null; ...

Sending an array or list of files from AJAX to the Controller

I have a task to upload multiple files and pass them to my Controller's Action. The current code is functional, but I feel there could be room for improvement as it's somewhat manual. I need to display file upload elements based on the number of ...

I'm having trouble getting my home.js to render in the outlet component

After using Material-UI to create navbar.js, I encountered an issue where the other component was not rendering in the <Outlet/> Component RootLayout.js import { Outlet } from "react-router-dom"; import NavBar from "../component/NavBa ...

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

Padding for the initial element in a carousel display

I am currently working on implementing owl carousel with stage padding. My goal is to use the carousel with loop:false, and have the first item displayed without left padding, while maintaining consistent padding for both items on the left and right after ...

What is the best way to send a parameter to a Javascript .done callback from a .success method?

Is there a way to transfer information from a .success function to a done function? $.ajax({ url: "/Asgard/SetLanguagesElf", success: function () { var amount = 7; }, error: function () { alert("SetLanguagesElf"); }, type: &apo ...

The Bootstrap data-target and aria-controls attributes are failing to activate the designated id element

I have implemented various elements to toggle the display of information on my HTML website. While I've successfully created buttons, nav-tabs, and modals, clicking on the trigger element doesn't reveal the associated content. I've even doub ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Select component experiencing issue with Material Ui label breaking

I've been working on implementing a select component, which is new to me. However, I'm encountering an issue with my MUI-select component. The label of the select element is no longer syncing properly with the select component itself as shown in ...

The circular reference error in Typescript occurs when a class extends a value that is either undefined, not a constructor,

Let me begin by sharing some context: I am currently employed at a company where I have taken over the codebase. To better understand the issue, I decided to replicate it in a new nestjs project, which involves 4 entities (for demonstration purposes only). ...

Have you considered utilizing "call for('express')()" instead?

When creating a simple Web server with NodeJS and Express, most tutorials provide examples like the following: const express = require('express'); const app = express(); app.listen(3000, () => console.log("Started")) app.get(' ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...

What is the best way to implement the nth:child selector in conjunction with the each function for handling JSON data in

Here is the HTML code I have written: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Flickr Feed</title> <link href="../_css/site.css" rel="stylesheet"> <link rel="stylesheet" type= ...

The functionality of IE's .attr disabled feature appears to be ineffective

My function to check if a product is available overnight is not functioning properly in Internet Explorer, although it works fine in other browsers. function checkOvernight() { id = $_2("[name='product']").val(); if(id.length > 0) { ...

Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 t ...

CKEditor5: Unable to access the 'pluginName' property because it is undefined

I am facing a challenge in creating a custom image plugin for CKEditor that can seamlessly integrate with my own image upload system. While trying to set up this plugin, I encountered some difficulties. Oddly enough, the "out-of-the-box" plugins work perfe ...

In HTML, specify that the height of both the `html` and

I am facing an issue with the container-about div. I have set its height to 100% so that the div occupies the entire width and height after the header div. The problem is that currently, I cannot scroll to view the full text. It would be great if there wa ...