在表单中乘以两个值

时间:2013-12-03 05:31:23

标签: javascript html html5

对于我的代码,我试图将2个参数调用到函数中。离开第二个输入框后,将两个数字相乘并将其放在第三个文本框中。如果前两个输入框中的任何一个为空,则将它们涂成浅红色。到目前为止,这是我的代码,我错过了什么?

使用Javascript:

function multiply(one, two) {
if(one==""){
this.style.color='red';
}
if(two==""){
this.style.color='red';
}
else{
txt1=one * two;
return txt1;
}

}

HTML5:

First Value: <input type="text" name="mFirst" />
Second Value: <input type="text" name="mLast" onblur="multiply(mFirst.value, mLast.value)" />
Multiplication of First and Second Value: <input type="text" name="answer">

4 个答案:

答案 0 :(得分:5)

<input … onblur="multiply.call(this,this.form.elements.mFirst.value,this.form.elements.mLast.value)" >
function multiply(one, two) {
  if(one && two){
    this.form.elements.answer.value = one * two;
  } else {
    this.style.color='red';
  }
}

空字符串是非真值,因此one && two只有在两个值都不是空字符串时才会为真。

使用call可以设置函数内使用的this的值。

演示:http://jsfiddle.net/b5Ltt/

您可能需要查看HTML5 <output> element

答案 1 :(得分:2)

您没有将this传递给multiply()函数。

如果您想更改this.style,可以将this作为参数传递。

此外,您应该将mFirst.value更改为this.form.elements.mFirst.value,将mLast.value改为First Value: <input type="text" name="mFirst" /> Second Value: <input type="text" name="mLast" onblur="multiply( this , mFirst.value, mLast.value)" /> Multiplication of First and Second Value: <input type="text" name="answer">

HTML:

function multiply( _this, one, two) {
    var txt1 = 0;
    if(one=="" || two==""){
        // Should set both colors to red
        _this.form.elements.mFirst.style.color = 'red';
        _this.form.elements.mLast.style.color= 'red';
    }else{

        // parse float in the case of a decimal and set de
        one = parseFloat(one);
        two= parseFloat(two);

        txt1 = one * two;
        _this.form.elements.answer.value = txt1;
    }
}

JavaScript的:

{{1}}

答案 2 :(得分:0)

First Value: <input type="text" name="mFirst" id="mFirst" />
Second Value: <input type="text" name="mLast" id="mLast" onblur="multiply()" />
Multiplication of First and Second Value: <input type="text" name="answer" id="answer" />

function multiply()
{
    var num_one = document.getElementById('mFirst').value;
    var num_two = document.getElementById('mLast').value;

    if(typeof num_one === 'number' && typeof num_two === 'number')
    {
        document.getElementById('answer').value = (parseInt(num_one) * parseInt(num_two));
    }
    else
    {
        document.getElementById('answer').style.color = 'red'; // not recommended method
    }




}

答案 3 :(得分:0)

使用类似的说明,为什么这不起作用?

function monetaryfields()
{
if (multiply) { total.value = unitary.value * quantity.value; }
else { unitary.value = total.value / quantity.value; }
}

<form>
<ul>
<li>Quantity: <input type="text" name="quantity" onblur="monetaryfields.call(true)" /></li>
<li>Unitary: <input type="text" name="unitary" onblur="monetaryfields.call(true)" /></li>
<li>Total: <input type="text" name="total" onblur="monetaryfields.call(false)" /></li>
</ul>
</form>