【问题标题】:javascript function does not work when two input field values are entered输入两个输入字段值时,javascript函数不起作用
【发布时间】:2018-02-05 18:23:00
【问题描述】:

当我运行它并单击提交时,它仅在我没有在表单中输入两个值时才起作用。如果我只输入一个字段或没有数据,那么它会按预期返回,但是当我同时输入城镇和电子邮件时,userText 在屏幕上闪烁然后消失。我错过了什么??感谢您的帮助....

    <html>

<form>
  <fieldset>
    <label>What's Your Home Town?
        <input type="text" id="town" size="40" maxlength="60" required>
    </label>    
    <label>Email Address?
        <input type="email" id="email" size="40" maxlength="60" required>
        </label>
    <label>Submit
    </label>
        <input type="submit" value="Submit" onclick="validateForm();">
  </fieldset>
        <p id = "text"></p>

</form>

<script>



        function validateForm() {
            var userTown = document.getElementById('town').value;
            var userEmail = document.getElementById('email').value;
            var userText = userTown +'\'s a Great Town!' + ' click this link to email someone who cares ' + userEmail;
            //alert(userText + ' Follow This Link to Send an Email to Someone who Cares ' + userEmail);
           document.getElementById('text').innerHTML=userText;    

        }

        </script>
</html>

【问题讨论】:

  • 提交按钮提交,所以我并不感到惊讶....

标签: javascript innerhtml getelementbyid


【解决方案1】:

由于表单中有submit 类型按钮,因此表单已提交。将其更改为button 类型将解决您的问题

function validateForm() {
  var userTown = document.getElementById('town').value;
  var userEmail = document.getElementById('email').value;
  var userText = userTown + '\'s a Great Town!' + ' click this link to email someone who cares <a href="mailto' + userEmail +'">' + userEmail +'</a>';
  //alert(userText + ' Follow This Link to Send an Email to Someone who Cares ' + userEmail);
  document.getElementById('text').innerHTML = userText;

}
<form>
  <fieldset>
    <label>What's Your Home Town?
        <input type="text" id="town" size="40" maxlength="60" required>
    </label>
    <label>Email Address?
        <input type="email" id="email" size="40" maxlength="60" required>
        </label>
    <label>Submit
    </label>
    <input type="button" value="Submit" onclick="validateForm();">
  </fieldset>
  <p id="text"></p>
</form>

【讨论】:

  • 成功了,谢谢..如何让 userEmail 显示为超链接?
  • @Corina 更新我的答案。如果有帮助,请接受并投票:)
  • 我如何接受和投票?我没有看到任何一个选项:(
  • 接受只需点击我的答案前面的勾号stackoverflow.com/help/accepted-answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多