如何获取input中输入的值

本文介绍了一种使用JavaScript/jQuery通过元素ID和名称属性获取HTML input输入框值的方法。提供了两种实用的代码实现方式。

提供两种方式,一种通过id获取,一种通过name获取:

电话:<input id="phone" name="mobile" type="number">
function(){
    var mobi = $("#phone").val();
    var mobi = $('input[name="mobile"]').val();
}

以上两种方式都能获得input输入值。

在HTML中获取input输入有多种方法,以下为你详细介绍: ### 使用JavaScript的`document.getElementById()`方法 若input元素有唯一的`id`属性,可使用`document.getElementById()`方法获取该元素,再通过`value`属性得到输入。示例代码如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <input type="text" id="myInput" value="示例文本"> <button onclick="getValue()">获取</button> <script> function getValue() { var inputElement = document.getElementById('myInput'); var inputValue = inputElement.value; console.log(inputValue); } </script> </body> </html> ``` ### 使用JavaScript的`document.querySelector()`方法 `document.querySelector()`方法可通过CSS选择器选择元素,获取input元素的输入。示例代码如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <input type="text" class="inputClass" value="示例文本"> <button onclick="getValue()">获取</button> <script> function getValue() { var inputElement = document.querySelector('.inputClass'); var inputValue = inputElement.value; console.log(inputValue); } </script> </body> </html> ``` ### 实时获取输入 实时获取input输入框中的需要`oninput`和`onpropertychange`属性来实现。由于`onpropertychange`属性为IE专属,而`oninput`属性支持大部分浏览器,包括IE9及以上的版本。示例代码如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <input type="text" oninput="showValue(this)" onpropertychange="showValue(this)"> <script> function showValue(input) { console.log(input.value); } </script> </body> </html> ``` ### 在ASP.NET后台获取input 在ASP.NET中,若要在后台获取input输入,需要为它添加`id`和`runat="server"`两个属性,然后通过`id`对应的名称`.Value`来获取输入。示例代码如下: ```html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <input type="text" id="myInput" runat="server" /> <asp:Button ID="btnGetValue" runat="server" Text="获取" OnClick="btnGetValue_Click" /> </form> </body> </html> ``` ```csharp using System; using System.Web.UI; public partial class _Default : Page { protected void btnGetValue_Click(object sender, EventArgs e) { string inputValue = myInput.Value; Response.Write("输入是:" + inputValue); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值