简体   繁体   中英

Trying to display a value when the select list option changes with onchange

What I'm trying to do is this: When a job is selected from a drop-down list, I want to populate the hourlyRate field in the totals table with an amount.
This is my dropdown list:

    <fieldset>
      <legend>What is your position?</legend>
      <select name="job" id="job">
        <option value="job0">Please select a position:</option>
        <option value="job1">Server/Bartender</option>
        <option value="job2">Greeter/Busser</option>
        <option value="job3">Kitchen Support</option>
      </select>
    </fieldset>

This is my totals table:

<div id="totals">
<table width="408">
<tr>
  <td width="214">Hourly Rate:</td><td width="57" id="hourlyRate"></td></tr>
</table>
</div>

This is my javascript:

var $ = function (id) {
return document.getElementById(id); 
}

function rateChange () {

var rate="";
    if ($('job').value == 'job0') {
    rate = '0';
    }
    if ($('job').value == 'job1') {
    rate = '12';
    }

    if ($('job').value == 'job2') {
    rate = '10';
    }

    if ($('job').value == 'job3') {
    rate = '11';
    }

$('hourlyRate').innerHTML = "$ " + rate;
}
window.onload = function () {
$('job').onchange = rateChange();
}

So if someone selects server/bartender from the dropdown list, I want the hourlyRate field in my totals table to display $12. I cannot figure out what I am doing wrong!

It looks like you're calling your function straight away, instead of telling it to be called on the onchange event:

$('job').onchange = rateChange();

So the return value of rateChange (nothing) is assigned to the onchange event.

Try this:

$('job').onchange = rateChange;

Now the rateChange function is the function that will be run when the onchange event fires.

if you want to add an handlerfunction to your event you must not add the brackets...

you have to wirte:

$('job').onchange = rateChange;

just tried... works fine. if you're adding the brackets the function will be called only one time in window.onload ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM