我有一个输入字段,其中将输入数值,而在另一个只读字段中,转换(计算)的值将动态显示。
我尝试使用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");
});
});
答案 0 :(得分:2)
你有几个问题:
==
运算符在您应该使用=
时分配值""
更新的代码应如下所示:
$(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
});
});
答案 1 :(得分:1)
问题出在你的代码的最后两行,其中语法略有不同。试试这个:
var converted = $("#strbasecurrency").val() * 0.73;
$("#strconvcurrency").val(converted);
您还需要在keypress
字段中使用keyup
或strbasecurrency
事件。