Giridhari Lal
Giridhari Lal

Reputation: 163

Using javaScript not getting value from dropdown and showing in div

javaScript code: Getting data from dropdown and showing into div inner html.

  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: onclick calling function showcost()

<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: here showing data, after calculating values.

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

Above code is doing nothing. I think I'm unable to find mistake.

Upvotes: 1

Views: 61

Answers (2)

Giridhari Lal
Giridhari Lal

Reputation: 163

javaScript Code:

function showDucost() {
        var days = document.getElementById("Ddays");
        var Dudays = days.options[days.selectedIndex].text;
        var pos = Dudays.indexOf("Days");
        var days = Dudays.slice(0,pos-1);
        var div = document.getElementById('Dcost');
        var treat_cost = <?php echo $HospitalPack->treat_cost ?>;
        div.innerHTML = treat_cost + days * 1200;
    }

Dropdown code:

<select class="form-control" name="Ddays" id="Ddays" onchange="showDucost()">
    <?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

div element code :

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

Upvotes: 0

LinJI
LinJI

Reputation: 126

First,'no.selectedIndex' is useless, you should remove the part 'no.'.Maybe you mean this way/??

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

Besides that, when you click the select element the browser would trigger 'onclick'.If you wanna update the view after you select a new option, you need to use 'onchange' instead. And I prefer you can show me the DOM structure without php codes.

Upvotes: 1

Related Questions