簡體   English   中英

將html值傳遞給javascript函數

[英]Passing html values into javascript functions

我正在制作一個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"; 

    }
}

給文本框一個id為“txtValue”並將輸入按鈕聲明更改為以下內容:

<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />

這是JSfiddle演示

我更改了您的HTML,並為您的輸入文本字段提供了有價值的ID。 我刪除了驗證順序函數的傳遞參數,而是使用document.getElementById()獲取文本字段的內容。 然后我用+order將str轉換為值,這樣你就可以檢查它是否大於零:

<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";
        }
    }

只需在輸入文本字段中輸入id屬性 -

<input type="text" maxlength="3" name="value" id="value" />

嘗試: if(parseInt(order)>0){....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM