基本上,我使用bootstrap作为我的CSS,但我遇到了一个问题。当我点击按钮(id="myQuestionButton"
)时,我希望它从输入框(id="myInput"
)获取输入并通过function checkQuestionWords()
运行。
以下是与输入和按钮有关的代码块:
<div class="input-append span9 offset3">
<form>
<input class="span4" type="text" id="myInput"
placeholder="Enter your question."></input>
<button class="btn" type="submit" id="myQuestionButton">
Let's check second.</button>
</form>
</div>
以下是打印初步结果的位置(目前仅在<div> </div>
中):
<div id="results"></div>
到目前为止,这是我的功能:
function checkQuestionWords(){
var theInput = document.getByElementId("myInput");
var theQuestion = theInput.trim();
var questionWords = ["who", "what", "where", "when", "why", "how"];
var isItGood = false;
for (var i=0, i<7; i++){
var holder1 = questionWords[i];
var holder2 = holder1.length;
if (theQuestion.substr(0,holder2) == questionWords[i]){
isItGood = true;
break;}
else{
isItGood = false;}}
if (isItGood == false){
document.getByElementId("results") = "Please enter a question...";}
//the above just reminds them to begin with a question word; see questionWords
else{
document.getByElementId("results") = "all is good";}
}
我尝试在onclick=checkQuestionWords()"
内部执行整个<button ...></button>
但由于某种原因无效。
答案 0 :(得分:1)
你问题就在于你正在使用
var theInput = document.getByElementId("myInput");
?
这将为您提供输入控件,其中id
为 myInput ,但不包含其中的文本。你想要更像
var theInput = document.getByElementId("myInput").value;
这将为您提供实际文本,然后您可以使用
将其分配给theQuestion
var theQuestion = theInput.trim();
答案 1 :(得分:0)
尝试这样的简单调用:
var btn = document.getElementById["myQuestionButton"];
btn.onClick = checkQuestionWords;
答案 2 :(得分:0)
上述代码中存在许多问题:
问题是:
getByElementId
应为getElementById
document.getByElementId("myInput")
应为document.getElementById("myInput").value;
document.getByElementId("results")
应为document.getElementById("results").innerHTML
请参阅下面的工作代码:
<script>
function checkQuestionWords() {
var theInput = document.getElementById("myInput").value;
var theQuestion = theInput;//.trim();
var questionWords = ["who", "what", "where", "when", "why", "how"];
var isItGood = false;
for (var i=0; i<7; i++){
var holder1 = questionWords[i];
var holder2 = holder1.length;
if (theQuestion.substr(0,holder2) == questionWords[i]){
isItGood = true;
break;}
else{
isItGood = false;}}
if (isItGood == false){
document.getElementById("results").innerHTML = "Please enter a question...";
}
//the above just reminds them to begin with a question word; see questionWords
else{
document.getElementById("results").innerHTML = "all is good";
}
return false;
}
</script>
<div class="input-append span9 offset3">
<input class="span4" type="text" id="myInput"
placeholder="Enter your question."></input>
<button class="btn" type="submit" id="myQuestionButton" onclick="checkQuestionWords();">
Let's check second.</button>
</div>
<div id="results"></div>