开发者

Add a value to an existing value

I want to add a number to another number that is defined by the user in a text box. The number that is added is determined by a string or code typed into a separate text box, controlled by an event handler.

Scenario

User enters a value of "70" into text box 1. User then types code "Valley" into text box 2 which should automatically add "28" to "70" in text box 1 and display the new value "开发者_运维百科98" in text box 1.

Is this possible ? If so what is the best way of approaching it. I have a basic understanding of JavaScript. Below is the start I have made, pretty pathetic I know. Any help is greatly appreciated because I am stumped as to where to go from here.

var TrackingCode = document.getElementById("textbox_2").value;
var textDay = "";
if (TrackingCode == "VALLEY") {


var TrackingCode = document.getElementById("textbox_2").value;
var box1 = document.getElementById("textbox_1");
if (TrackingCode == "VALLEY") {
    box1.value = Number(box1.value) + 28;
}

Note the Number cast is required, or you'll get 7028.


You can store all your codes in an object as a kind of dictionary:

var codes = {
    "VALLEY": 28,
    "FIELD" : 42,
    "MOUNTAIN" : 7,
    "STREAM" : 99,
    "PLATEAU" : 18
};

Then get the values and add them up like this:

var firstNumber = parseFloat(document.getElementById("textbox_1").value);
var trackingCode = document.getElementById("textbox_2").value;
if (isFinite(firstNumber) && trackingCode in codes)
{
    var codeValue = codes[trackingCode];
    var sum = firstNumber + codeValue;
}

Of course, you could also just use a <select> list box.

<select id="trackingCodeListBox">
    <option value="28">VALLEY</option>
    <option value="42">FIELD</option>
    <option value="7">MOUNTAIN</option>
    <option value="99">STREAM</option>
    <option value="18">PLATEAU</option>
</select>

Then you would just get the value of the the selected item:

var listBox = document.getElementById("trackingCodeListBox");
var selectedCode = listBox.options[listBox.selectedIndex].value;
var trackingCode = parseFloat(selectedCode);  // or parseInt() if appropriate;


Thanks for the help.

function execute()
{
    var TrackingCode = document.getElementById("tracking_code").value;
    var box1 = document.getElementById("packageCostA");
    var num = document.getElementById("adults_nr").value;
    if (TrackingCode == "VALLEY") {
        packageCostA.value = Number(packageCostA.value) + 28*adults_nr.value;
    }
}

That's what I ended up with, it now works how I want it to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜