将html值传递到javascript函数
我正在制作一个javascript函数,我需要确认输入。我写了下面的代码,但它给出了负值,即“else”部分,即使我输入了一个有效值。有人可以提出一个解决方案吗?将html值传递到javascript函数
HTML文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript App</title>
<script type="text/javascript" src="app1.js">
</script>
</head>
<body><h1 id="heading1" style="text-align:center; height:auto; width:auto; font-family:'Arial Black', Gadget, sans-serif">Determinant of a nxn matrix</h1>
<p id="paragraph1" style="font-family:'Arial Black', Gadget, sans-serif"> This program allows you to compute the determinant of a nxn matrix</p>
<p>
Input the order of the matrix
<br />
<input type="text" maxlength="3" name="value" />
<input type="button" value="submit" onclick="verifyorder(value)" />
</p>
<p id="error"></p>
<p id="detspace"></p>
</body>
</html>
JavaScript文件:
function verifyorder(order){
;
if(order>0){
return true;
}
else{
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML="Sorry, you need to enter a positive integer value, try again";
}
}
我改变你的HTML,让你的输入文本框的ID的价值。我删除了您的验证函数的传递参数,并通过使用document.getElementById()来获取文本字段的内容。然后我转换海峡与+order
值,以便您可以检查它是否大于零:
<input type="text" maxlength="3" name="value" id='value' />
<input type="button" value="submit" onclick="verifyorder()" />
</p>
<p id="error"></p>
<p id="detspace"></p>
function verifyorder() {
var order = document.getElementById('value').value;
if (+order > 0) {
alert(+order);
return true;
}
else {
alert("Sorry, you need to enter a positive integer value, try again");
document.getElementById('error').innerHTML = "Sorry, you need to enter a positive integer value, try again";
}
}
如果我想将param带给javascripts? 'javascript:somefunc(someparams);'这样? – jboxxpradhana 2015-12-17 20:16:54
尝试:if(parseInt(order)>0){....
给文本框的“txtValue”一个ID,输入按钮声明更改为以下:
<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />
这里有更好的答案,它使用函数的参数。 – 2015-07-16 02:02:03
这个答案应该被接受。 – madrick 2016-12-10 01:59:56
简而言之id属性在您输入文本字段 -
<input type="text" maxlength="3" name="value" id="value" />
您发布明确的代码运行* *后出现的问题。我的猜测是你已经传入了一个*字符串*,而不是一个数字,但没有调用'verifyorder'的代码,我不知道。 – Malvolio 2011-03-15 18:01:09
您的代码中没有任何内容将称为“value”的(未定义的和未初始化的)Javascript变量与正好具有名称“value”的DOM元素相关联。您需要以某种方式告诉Javascript找到该输入元素并提取其值。 – 2011-03-15 18:03:53
我该怎么做? – 2011-03-15 18:05:27