Javascript 抓取表单字段并根据输入进行计算
我收到一个Javascript 抓取表单字段并根据输入进行计算,javascript,Javascript,我收到一个未定义的错误,不知道为什么这不起作用 它应该将租金除以室友的数量: 函数splitRent(){ var roommates=document.getElementById(“租金”); var rent=document.getElementById(“租金”); var rentEach=租金/室友; if(document.getElementById(“提交”)==true){ 文档。写下(“你们每人应支付”+“”+租金) }否则{ document.alert(“Gimme
未定义的
错误,不知道为什么这不起作用
它应该将租金除以室友的数量:
函数splitRent(){
var roommates=document.getElementById(“租金”);
var rent=document.getElementById(“租金”);
var rentEach=租金/室友;
if(document.getElementById(“提交”)==true){
文档。写下(“你们每人应支付”+“”+租金)
}否则{
document.alert(“Gimme信息”)
}
};代码>
室友分房器
室友:
租金:
这不应该是:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
您的结果总是得到“1”吗?您希望获取字段的值,而不是字段本身
document.getElementById()
返回节点,但您需要输入
字段的名称:
var rent = document.getElementById("rent").value;
而且,你得到的租金价值是原来的两倍;你也要检查一下室友
var roommates = document.getElementById("roommates").value;
最后,document.getElementById(“submit”)==true并不意味着什么:您正在将按钮节点与布尔值进行比较,这没有意义。如果要检查以确保两个字段都已填充,请尝试以下操作:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
目前,这允许人们输入非数字的东西;你可以做两件事来解决这个问题
使用parseInt()
/parseFloat()
确保您正在提取一个数字
在进行计算之前,请检查您是否确实有一个数字
你可以这样做:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
如果您使用我在上面所做的检查(rent&roommates
),验证将在那里进行(它检查空值和NaN
值)
函数splitRent(){
var roommates=parseInt(document.getElementById(“roommates”).value);
var rent=parseFloat(document.getElementById(“rent”).value);
var rentEach=租金/室友;
如果(室友和租金){
文档。写下(“你们每人应支付”+“”+租金)
}否则{
window.alert(“给我信息”)
}
};代码>
室友分房器
室友:
租金:
首先,您的代码将为两个变量室友和租金获取租金的值:),否则您需要在getElementById()的末尾添加.value
,您只需返回元素,不是它的值。在每个getElementById()
的末尾添加一个.value
可能也会有帮助;)(不,我没有否决投票)非常感谢!!我对房租/室友的情况感到很傻,但你真的帮我解决了!我显然是新来的。但有一个问题。。。如果我写window.alert(“你们每个人都应该支付”+“”+rentEach),我可以得到对splitRent的响应。但是,我无法使用document将其写入页面。write,这有什么原因吗?@dshesh我很高兴能帮上忙!如果我的答案解决了你的问题,请考虑,让我们双方都获益。