【问题标题】:how to link html form input to javascript function and showing the output [duplicate]如何将html表单输入链接到javascript函数并显示输出[重复]
【发布时间】:2018-11-16 12:50:14
【问题描述】:

我真的迷路了,不知道该怎么办。 我试图将输入的 html 表单链接到 java-script 函数。

但问题是我不知道我的步骤是否正确。另一件事是如何在页面上显示输出。

function fnCountVowels(string) {
  var getinput = document.getElementsbyid("Vowel1");
  console.log(Vowel1.value);

  for (i = 0 < getinput.length; i++) {
    chr = getinput.charat(i);

    if (Chr == "a" || (chr == "e") || (chr == "i") || (chr == "o") || (chr == "u")) {
      getinput = getinput + 1;
    }
  }

  return getinput;
}
<div id="Vowel" class="Tab">
  <form action=""  id="form" onsubmit="fnCountVowels(string)">
    Enter String: <br>
    <input id="Vowel1" type="text" name="Enter the string "><br><br>
    <button type="submit" onclick"fnCountVowels(string)">Click</button>
  </form>

【问题讨论】:

  • 请对您的代码进行布局以使其可读。删除多余的空行并使缩进合理。
  • 除了“我的代码不起作用,请帮忙”之外,这里还有什么具体问题吗?

标签: javascript html forms


【解决方案1】:

这是一个基于您的代码的解决方案,但对其进行了一些简化和“现代化”:

function countVowels() {
  var text = document.forms["CountVowels"].text.value,
  nmrOfVowels = 0;
  console.log( text);
  for (let i=0; i < text.length; i++) {
let char = text.charAt(i);
if ("aeiou".includes( char)) {
  nmrOfVowels = nmrOfVowels + 1;
}
  }
  console.log("Number of vowels: ", nmrOfVowels);
  document.getElementById("showResult").textContent = "Number of vowels: "+ nmrOfVowels;
}
<form id="CountVowels">	
  <label>Enter text: <input name="text"/></label>
  <button type="button" onclick="countVowels()">Count vowels</button>
</form>
<p id="showResult"></p>

【讨论】:

    【解决方案2】:

    在下面试试这个,

    function fnCountVowels()
    {
      var vowelCount = 0;
      var vowels = [];
      var getinput = document.getElementById("Vowel1").value;
     
      for (var i = 0; i < getinput.length; i++) 
      {
    	  chr = getinput.charAt(i);
        
        if (chr == "a" || (chr == "e") || (chr == "i") || (chr == "o") || (chr == "u"))
        {
            vowelCount += 1;
            vowels.push(chr);
        }
      }
    
    console.log("Input: " + getinput);
    console.log("Vowels Count: " + vowelCount);
    console.log("Vowels: " + vowels);
    }
    <div id="Vowel" class="Tab">
    
    <form>
    	
    Enter String: <br>
    <input id="Vowel1" type="text" name="Enter the string "> <br><br>
    
    	<button type="button" onclick="fnCountVowels()"> Click </button>
    	
    
    </form>
    
    </div>

    【讨论】:

    • 请注意,在代码块中使用var(如for (var i = 0;...)是一种代码异味,因为它表明声明了块范围变量,但事实并非如此!
    • 要在数组末尾添加一个元素,我们使用push。因此,您应该编码 vowels.push( chr)!
    • 同意!只是添加了它的基本理解方式。。但是,现在修改!
    猜你喜欢
    • 2021-07-15
    • 2019-04-26
    • 2014-09-11
    • 1970-01-01
    • 2023-04-02
    • 2021-08-26
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多