TaraX
TaraX

Reputation: 59

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!

Upvotes: 0

Views: 710

Answers (2)

JuHwon
JuHwon

Reputation: 2063

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...

Upvotes: 0

Lee Kowalkowski
Lee Kowalkowski

Reputation: 11751

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.

Upvotes: 1

Related Questions