如何获取<input>的值?

问题描述 投票:0回答:4

如何获得
<input>
的值

  1. 我正在尝试通过 iframe 制作页面查看器,所以。我已经搜索了一些有帮助的东西。但没有任何事情能够正确地提供帮助。我试过了

我使用的代码不起作用。

在W3Docs上找到的,我使用了这部分代码...

function getInputValue() {
  // Selecting the input element and get its value 
  let inputVal = document.getElementsByClassName("inputClass")[0].value;
  // Displaying the value
  alert(inputVal);
}
<input type="text" placeholder="Type " id="inputId" class="inputClass">
<button type="button" onclick="getInputValue();">Get Value</button>

它没有正确提醒输入的值。

我也尝试过这个,它应该在函数内部有一个变量,我可以简单地将其放入按钮的

onclick

var input = document.getElementById("input_id").value;

这也没有回报。当我把它放在按钮内时什么也没发生。

额外

有什么来源可以找到类似的东西吗?

javascript html
4个回答
2
投票

获取输入值的最佳方法是制作表格:


    <form class="my-form">
        <input type="text" placeholder="Type " name="my-input">
        <button>Get Value</button>
    </form>

    <script>
        let form = document.querySelector(".my-form");

        form.addEventListener("submit", function (e) {
        e.preventDefault() // This prevents the window from reloading
        
        let formdata = new FormData(this);
        let input = formdata.get("my-input");

        alert(input);
        });
    </script>

这是从输入获取数据的最佳方式。您只需使用 new FormData() 输入表单的值,然后使用 formdata.get("input_name")

获取输入值

1
投票

就像@Kinglish所说,你在使用getElementById时犯了一个拼写错误。

 <input type="text" placeholder="Type " id="inputId" class="inputClass">
<button type="button" onclick="getInputValue();">Get Value</button>
<script>
  function getInputValue() {
    let inputVal = document.getElementById("inputId").value;
    alert(inputVal);
  }
</script>

应该是“inputId”,而不是“input_id”。


0
投票

我不明白为什么对象之间有一个“[0]”。也许这可以帮助你。先声明变量,然后使用它。

<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>

function myFunction() {
  var x;
  x = document.getElementById("numb").value;
}

0
投票

要使用在输入标签中输入的值,请使用以下代码。 在以下代码中,输入标记中输入的值被推送到名为 myLead 的数组中 `

let inputBtn = document.querySelector("#input-btn")
let myLead = [];
const inputEl = document.getElementById("input-el");





 inputBtn.addEventListener("click", function(){
        myLead.push(inputEl.value);//here value of input field is pushed in array
        console.log(myLead)
        })

`

© www.soinside.com 2019 - 2024. All rights reserved.