如何在代码中定义文本字段值

how to define a text field value in code

本文关键字:文本 字段 定义 代码      更新时间:2023-09-26
<form id="form2" name="form2" action="">
   <div class="form_colour" id="formcolour"><img src="../Images/red_car.jpg" alt=""   width="370" height="124" />This car is
      <label for="textarea"></label>
      <input name="text_1" type="text" class="form_colour" id="text_1" />
   </div>
   <p>&nbsp;</p>
   <p><img src="../Images/green_car.jpg" width="370" height="124" />This car is
      <input name="text_2" type="text" class="form_colour" id="text_2" />
   </p>
   <p>
      <img src="../Images/Yellow_car.jpg" width="370" height="124" />This car is
      <input name="text_3" type="text" class="form_colour" id="text_3" maxlength="8" />
   </p>
   <p>
      <input name="confirm" type="button" class="form_colour" id="confirm" value="Confirm" />
   </p>
</form>

我目前有一个表单的以下代码,其中包含 3 个文本字段(表单的代码在此上方,Javascript 代码在此文本下方)。

我的目标是基于文本值的输入,用户要么收到一条消息并留在页面上,要么如果他们是正确的,则会收到一条消息并转到另一个页面。我之前为下拉列表做过这个。我所做的只是将变量从下拉列表名称更改为文本字段名称。现在当我运行它时,没有任何反应,我需要做更多的事情???

</script>
<script type="text/javascript">
function checkValues() {  // this line must be within the script tags
   var a = document.form2.text_1.value;    
   var b = document.form2.text_2.value; 
   var c = document.form2.text_3.value; 
   if (a == "red" && b == "green" && c == "yellow"){ 
      alert ("Correct you have won press OK for your Reward!") 
      window.location.href = "Reward.html";   // redirect to new page
   } 
   else { 
      alert ("Not right Please try again!"); 
      window.location.href = "Money_Match.html";
   } 
}
</script>
</script>

您尚未在单击按钮时调用脚本,请在此处查看工作示例 http://jsfiddle.net/3CgcH/7/

您需要为将调用checkValues函数的按钮指定 onclick 处理程序

<input name="confirm" type="button" class="form_colour" id="confirm" value="Confirm" onclick="checkValues();" />

更正确的方法是使用 addEventListenerattachEvent 在 HTML 元素上注册事件