使用jquery进行动态货币转换

时间:2014-05-15 15:17:14

标签: jquery

我有一个输入字段,其中将输入数值,而在另一个只读字段中,转换(计算)的值将动态显示。

我尝试使用jQuery但它无法正常工作。

Html

<form name="curconvert" method="get" action="script/conversion.php">
  <div class="field-row conversion">
       <div class="field1"><input type="text" name="strbasecurrency" id="strbasecurrency" tabindex="1"  value="Start typing..." onfocus="if (this.value == 'Start typing...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Start typing...';}" /></div>
        <div class="field2">=</div>
        <div class="field3"><input type="text" name="strconvcurrency" id="strconvcurrency" value="Result" readonly class="converted"></div>
   </div>
</form>

的jQuery

$(document).ready(function() {


$("#strbasecurrency").keydown(function (e) {
    $('.field-row input').css({'color':'#162d3a'});
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) || 
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
    $converted == ($("#strbasecurrency").val() * 0.73);
    $("#strconvcurrency").val("$converted");
   });
 });

JS Fiddle

2 个答案:

答案 0 :(得分:2)

你有几个问题:

  1. 您使用$ converted变量而不使用var。
  2. 您曾尝试使用==运算符在您应该使用=时分配值
  3. 当您尝试将值设置为输入字段时,您将值括在""
  4. 更新的代码应如下所示:

    $(document).ready(function() {
    
    
    $("#strbasecurrency").keydown(function (e) {
        $('.field-row input').css({'color':'#162d3a'});
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
                //added "var" and used = instead of ==
        var $converted = ($("#strbasecurrency").val() * 0.73); 
        $("#strconvcurrency").val($converted); //removed double quotes around $converted
    
    });
    

    });

    Updated fiddle

答案 1 :(得分:1)

问题出在你的代码的最后两行,其中语法略有不同。试试这个:

var converted = $("#strbasecurrency").val() * 0.73;
$("#strconvcurrency").val(converted);

您还需要在keypress字段中使用keyupstrbasecurrency事件。

Updated fiddle