gpt4 book ai didi

javascript - 用户输入生成子字符串

转载 作者:行者123 更新时间:2023-11-28 05:55:41 49 4
gpt4 key购买 nike

在我的程序中,我有三个文本字段。在其中一个中,您应该填写一些文本,在另外两个中,您应该填写两个数字。单词数量较大的文本字段必须比单词数量较小的文本字段具有更大的值。但是,该数字必须小于用户输入文本的长度。

每当我运行该程序时,JavaScript 控制台都会说它无法读取子字符串 null 的属性。这是我的代码的相关部分。

<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!
<script type = "text/javascript">
var t = document.getElementById("t");
var s = document.getElementById("small");
var l = document.getElementById("large");
function sub_str() {
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((regex_num.test(s)) || (regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
</script>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>

最佳答案

将 DOM 元素选择移动到函数中,并读取其值。试试这个:

<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!
<script type = "text/javascript">

function sub_str() {
var t = document.getElementById("t").value;
var s = document.getElementById("small").value;
var l = document.getElementById("large").value;
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((!regex_num.test(s)) || (!regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
</script>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>

关于javascript - 用户输入生成子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37717030/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com