2011-02-11 35 views
0
<script type="text/javascript"> 
function compute(calcval, val) 
{ 
    var txtweeklyMailing = Number(document.getElementById(val).value); 
    var total = txtweeklyMailing * 25; 
    var _total = total.toFixed(2); 
    var _stotal = _total + ''; 
    document.getElementById(calcval).value = _stotal; 
    } 
</script> 
<p>Number of weekly mailings @Html.TextBoxFor(m => m.WeeklyMailings, new { id = "weeklymailing", onblur = "return:compute('txtpostcardperweek', 'weeklymailing')" }) x 25</p> 
<p>=</p> 
<p>@Html.TextBoxFor(m => m.PostcardsperWeek, new Dictionary<string, object>() { {"id", "txtpostcardperweek"}, { "readonly", "true" } }) Total postcards per week</p> 

我需要使用一个文本框的onblur来计算用户输入的值为25,并将结果显示在下面的文本框中。我将如何传递onblur事件中的文本框值?在javascript中为MVC计算函数

回答

2

尝试这样的:

@Html.TextBoxFor(
    m => m.WeeklyMailings, 
    new { 
     id = "weeklymailing", 
     onblur = "compute('txtpostcardperweek', 'weeklymailing')" 
    } 
) 

,或者如果你想使用不显眼的JavaScript的使用jQuery:

<script type="text/javascript"> 
    $(function() { 
     $('#weeklymailing').blur(function() { 
      var txtweeklyMailing = Number($(this).val()); 
      var total = txtweeklyMailing * 25; 
      $('#txtpostcardperweek').val(total.toFixed(2)); 
     }); 
    }); 
</script> 
<p> 
    Number of weekly mailings 
    @Html.TextBoxFor(m => m.WeeklyMailings, new { id = "weeklymailing" }) 
    x 25 
</p> 
<p>=</p> 
<p> 
    @Html.TextBoxFor(m => m.PostcardsperWeek, new { id = "txtpostcardperweek", @readonly = "readonly" }) 
    Total postcards per week 
</p> 

个人而言,我倾向于第二种方法,因为你不混合的JavaScript和标记从而降低了你的HTML页面的大小,你可以把JavaScript放到一个单独的静态文件中,这个文件可以被客户端浏览器缓存。

+0

谢谢Darin。我使用了第二个选项。非常感谢。 – bladerunner 2011-02-11 21:26:54