问题描述
我目前正在构建一个网站,以了解有关 HTML 如何与 CSS 和 JS 交互的更多信息。我的目标是让用户输入不少于 256 个字符(最少:256 个字符),选择 ASCII 或 EBCDIC,然后点击“运行!”按钮以 ASCII 或 EBCDIC 格式打印字符串。我面临两个挑战:尽管在 JS 文件中说明了这一点,但我无法让程序返回空值(如果字符串的长度小于 256 个字符)。此外,我已经编写了打印出 ASCII 的代码,但是在将 ASCII 和 EBCDIC 与供用户选择的单选按钮集成在一起时遇到了麻烦。下面是我写的代码:
function myFunction() {
let str = document.getElementById("text_id");
if (str.value == "" && str.length >= 256) {
str.focus();
return;
} else if (str.value == "" && str.length < 256) {
return null;
}
let a = "ASCII Code is == > ";
document.getElementById("demo").innerHTML = a + str.value.charCodeAt(0);
}
body {
font: 12pt Arial;
}
input[type=radio]+label::before {
border-radius: 10px;
}
input {
border: 2px solid currentcolor;
}
input:invalid {
border: 2px dashed red;
}
input:invalid:focus {
background-image: linear-gradient(pink,lightgreen);
}
<body style="text-align:center;">
<label for="text">Enter a text that is at least 256 characters long</label>
<input type="text" id="text_id" name="text" minlength="256">
<p>Select the following:</p>
<div>
<input id="ascii" type="radio" name="encoding" value="ascii">
<label for="ascii">ASCII</label>
</div>
<div>
<input id="ebcdic" type="radio" name="encoding" value="ebcdic">
<label for="ebcdic">EBCDIC</label>
</div>
<button onclick="myFunction()" type="button">"Run!"</button>
<label for="button">"Run!"</label>
<p id="demo" style="color:red;">
</body>
尽管我输入的字符串长度小于 256,但我无法理解为什么程序返回 ASCII 值。我想确保用户只能输入长度为 256 或更大的字符串。还想知道如何确保用户在提交字符串之前选择单选按钮(ASCII 或 EBCDIC)。
解决方法
您的条件:
-
str.value == ""
与空值比较,你的意思是不是空的!=
吗? -
str.length
str 是html标签,没有长度,应该是str.value.length
你需要循环检查收音机是否是checked
function myFunction() {
let str = document.getElementById("text_id");
// check the radios
let isRadioChecked = false;
document.querySelectorAll('input[type="radio"]').forEach(function(radio) {
if (radio.checked) {
isRadioChecked = true;
}
})
if (!isRadioChecked) {
console.log('radio not checked,return');
return;
}
if (str.value.length >= 256) {
let a = "ASCII Code is == > ";
document.getElementById("demo").innerHTML = a + str.value.charCodeAt(0);
str.focus();
return;
}
else if (str.value.length < 256) {
console.log('null');
return null;
}
}
body {
font: 12pt Arial;
}
input[type=radio]+label::before {
border-radius: 10px;
}
input {
border: 2px solid currentcolor;
}
input:invalid {
border: 2px dashed red;
}
input:invalid:focus {
background-image: linear-gradient(pink,lightgreen);
}
encod
<label for="text">Enter a text that is at least 256 characters long</label><br>
<input type="text" id="text_id" name="text" minlength="256">
<p>Select the following:</p>
<div>
<input id="ascii" type="radio" name="encoding" value="ascii">
<label for="ascii">ASCII</label>
</div>
<div>
<input id="ebcdic" type="radio" name="encoding" value="ebcdic">
<label for="ebcdic">EBCDIC</label>
</div>
<button onclick="myFunction()" type="button">"Run!"</button>
<label for="button">"Run!"</label>
<p id="demo" style="color:red;">