【发布时间】:2013-04-29 01:56:02
【问题描述】:
这将是第一次,所以我不会以“我是编程新手”作为我的问题的开头(哎呀)。我会直接进入它:
这是我的 HTML 代码:
<div class="hide" id="hide2">
<div class="inputselect">
<p>
<label>What is your budget?</label>
</p>
<p>
Minimum: $<input type="text" id="minBud" name='minBud'><br />
Maximum: $<input type="text" id="maxBud" name='maxBud'><br />
<br />
</p>
<button type="button" class="next" id="next3">Next</button>
<button type="button" class="prev" id="prev2">Previous</button>
</div>
</div>
这是我正在努力解决的 jQuery/javascript 代码 sn-p:
$("#next3").click(function(){
if (typeof $("#minBud").val() === "number" && typeof $("#maxBud").val() === "number") {
gunsPrice();
$("#hide3").slideDown("fast");
$("#hide2").slideUp("fast");
} else {
alert("Please only enter NUMBERS into the budget fields");
}
});
我希望看到的是:如果 minBud 和 maxBud 字段中的条目是数字,则运行 gunsPrice() 并提出下一个问题(HTML 表单)。
我尝试了几种不同的方式来改变语法,但无论我怎么做,数字都会继续触发alert。
注意:我可以让typeof 运算符在gunsPrice() 中正常运行(使用通过getElementById 收集的变量,但这在此应用程序中对我没有任何好处;它总是转到下一个问题(由于我设置 jQuery 代码的方式)。
谢谢!
【问题讨论】:
-
您应该回显 typeof 并查看代码认为它是什么。可能是“字符串”,因为它来自表单元素。
-
val总是返回一个字符串。您需要对其进行解析以验证用户输入的是有效数字。 -
用你的代码发布一个 jsfiddle。同时,console.log() 两个输入的 .val() 与你的 if/then 分开。验证每个的 typeof 是什么。
-
根据文档 val() 可以返回数字,但文档没有提到在什么情况下它将返回数字。 api.jquery.com/val
-
我尝试了 Cfreak 的建议(不知道为什么我之前没有想到...),变量被识别为“对象”。我假设将我的条件从“数字”更改为“对象”是不好的:)
标签: javascript jquery typeof