简体   繁体   English

当选择列表选项随onchange更改时尝试显示一个值

[英]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. 我想做的是:从下拉列表中选择一项工作时,我想在总数表中的hourlyRate字段中填充一个数量。
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: 这是我的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. 因此,如果有人从下拉列表中选择服务器/调酒师,我希望我的合计表中的hourlyRate字段显示$ 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: 看起来您正在立即调用函数,而不是告诉它在onchange事件上被调用:

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

So the return value of rateChange (nothing) is assigned to the onchange event. 因此, rateChange的返回值(什么都没有)分配给onchange事件。

Try this: 尝试这个:

$('job').onchange = rateChange;

Now the rateChange function is the function that will be run when the onchange event fires. 现在, rateChange函数是在onchange事件触发时将运行的函数。

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 ... 如果添加括号,则该函数在window.onload仅被调用一次...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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