[英]How do I get the value of text input field using JavaScript?
我正在使用 JavaScript 進行搜索。 我會使用一個表單,但它會弄亂我頁面上的其他內容。 我有這個輸入文本字段:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
這是我的 JavaScript 代碼:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
如何從文本字段中獲取值到 JavaScript 中?
有多種方法可以直接獲取輸入文本框值(無需將輸入元素包裝在表單元素中):
方法一:
document.getElementById('textbox_id').value
獲取所需框的值例如
document.getElementById("searchTxt").value;
注意:方法 2,3,4 和 6 返回元素的集合,因此使用 [whole_number] 來獲取所需的出現次數。 對於第一個元素,使用 [0],對於第二個元素,使用1 ,依此類推...
方法二:
使用
document.getElementsByClassName('class_name')[whole_number].value
返回一個 Live HTMLCollection例如
document.getElementsByClassName("searchField")[0].value;
如果這是您頁面中的第一個文本框。
方法三:
使用
document.getElementsByTagName('tag_name')[whole_number].value
它還返回一個實時 HTMLCollection例如
document.getElementsByTagName("input")[0].value;
,如果這是您頁面中的第一個文本框。
方法四:
document.getElementsByName('name')[whole_number].value
也 > 返回一個活動的 NodeList例如
document.getElementsByName("searchTxt")[0].value;
如果這是您頁面中第一個名稱為“searchtext”的文本框。
方法五:
使用強大的
document.querySelector('selector').value
,它使用 CSS 選擇器來選擇元素例如
document.querySelector('#searchTxt').value;
由 id 選擇document.querySelector('.searchField').value;
按班級選擇document.querySelector('input').value;
由標記名選擇document.querySelector('[name="searchTxt"]').value;
按名稱選擇
方法六:
document.querySelectorAll('selector')[whole_number].value
也使用 CSS 選擇器來選擇元素,但它會將具有該選擇器的所有元素作為靜態節點列表返回。例如
document.querySelectorAll('#searchTxt')[0].value;
由 id 選擇document.querySelectorAll('.searchField')[0].value;
按班級選擇document.querySelectorAll('input')[0].value;
由標記名選擇document.querySelectorAll('[name="searchTxt"]')[0].value;
按名稱選擇
支持
Browser Method1 Method2 Method3 Method4 Method5/6
IE6 Y(Buggy) N Y Y(Buggy) N
IE7 Y(Buggy) N Y Y(Buggy) N
IE8 Y N Y Y(Buggy) Y
IE9 Y Y Y Y(Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N IE=Internet Explorer
FF3.5/FF3.6 Y Y Y Y Y FF=Mozilla Firefox
FF4b1 Y Y Y Y Y GC=Google Chrome
GC4/GC5 Y Y Y Y Y Y=YES,N=NO
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y(Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y
有用的鏈接
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
我會創建一個變量來存儲這樣的輸入:
var input = document.getElementById("input_id").value;
然后我會使用該變量將輸入值添加到字符串中。
= "Your string" + input;
您應該能夠輸入:
var input = document.getElementById("searchTxt"); function searchURL() { window.location = "http://www.myurl.com/search/" + input.value; }
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
我確信有更好的方法可以做到這一點,但這個方法似乎適用於所有瀏覽器,並且它需要對 JavaScript 的最少了解來制作、改進和編輯。
您也可以通過標簽名稱調用,如下所示: form_name.input_name.value;
因此,您將具有特定形式的確定輸入的特定值。
<input type="text" onkeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value) {
window.open("http://www.google.com/search?output=search&q=" + value)
}
</script>
您可以通過searchTxt.value
讀取值
function searchURL() { let txt = searchTxt.value; console.log(txt); // window.location = "http://www.myurl.com/search/" + txt; ... } document.querySelector('.search').addEventListener("click", ()=>searchURL());
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/> <button class="search">Search</button>
在 Chrome 和 Firefox 中測試:
通過元素 id 獲取值:
<input type="text" maxlength="512" id="searchTxt" class="searchField"/>
<input type="button" value="Get Value" onclick="alert(searchTxt.value)">
在表單元素中設置值:
<form name="calc" id="calculator">
<input type="text" name="input">
<input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>
https://jsfiddle.net/tuq79821/
還可以查看 JavaScript 計算器實現: http ://www.4stud.info/web-programming/samples/dhtml-calculator.html
來自@bugwheels94 的更新:使用此方法時請注意此問題。
當您有更多輸入字段時,您可以使用 onkeyup。 假設你有四個或 input.then document.getElementById('something').value
很煩人。 我們需要寫 4 行來獲取輸入字段的值。
因此,您可以創建一個函數,在 keyup 或 keydown 事件上將值存儲在對象中。
例子 :
<div class="container">
<div>
<label for="">Name</label>
<input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Age</label>
<input type="number" name="age" id="age" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Email</label>
<input type="text" name="email" id="email" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Mobile</label>
<input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
</div>
<div>
<button onclick=submitData()>Submit</button>
</div>
</div>
javascript:
<script>
const data={ };
function handleInput(e){
data[e.name] = e.value;
}
function submitData(){
console.log(data.fname); //get first name from object
console.log(data); //return object
}
</script>
如果您的input
是在form
中並且您希望在提交后獲得價值,您可以這樣做
<form onsubmit="submitLoginForm(event)">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<script type="text/javascript">
function submitLoginForm(event){
event.preventDefault();
console.log(event.target['name'].value);
console.log(event.target['password'].value);
}
</script>
這種方式的好處:例如,您的頁面有2 個form
用於輸入sender
和receiver
信息。
如果您不使用form
獲取價值,那么
- 您可以為每個字段設置 2 個不同的id
(或tag
或name
...),例如sender-name
和receiver-name
, sender-address
和receiver-address
,...
- 如果您為 2 個輸入設置相同的值,那么在getElementsByName
(或getElementsByTagName
...)之后,您需要記住 0 或 1 是sender
或receiver
。 后面如果在html中改變了2個form
的順序,需要再次查看這段代碼
如果你使用form
,那么你可以使用name
, address
, ...
function handleValueChange() { var y = document.getElementById('textbox_id').value; var x = document.getElementById('result'); x.innerHTML = y; } function changeTextarea() { var a = document.getElementById('text-area').value; var b = document.getElementById('text-area-result'); b.innerHTML = a; }
input { padding: 5px; } p { white-space: pre; }
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()"> <p id="result"></p> <textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea> <p id="text-area-result"></p>
<input id="new" >
<button onselect="myFunction()">it</button>
<script>
function myFunction() {
document.getElementById("new").value = "a";
}
</script>
可以使用 form.elements 獲取表單中的所有元素。 如果一個元素有 id,它可以通過 .namedItem("id") 找到。 例子:
var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;
資料來源: w3schools
簡單的js
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
}
function searchURL() {
window.location = 'http://www.myurl.com/search/' + searchTxt.value
}
所以基本上searchTxt.value
將返回id='searchTxt'
的輸入字段的值。
您可以通過以下代碼使用 JavaScript 獲取文本輸入字段的值: input_text_value = console.log(document.getElementById("searchTxt").value)
textObject
有一個value
屬性,您可以設置和獲取此屬性。
要進行設置,您可以分配一個新值: document.getElementById("searchTxt").value = "new value"
如果您使用的是 jQuery,那么通過使用插件 formInteract,您只需要這樣做:
// Just keep the HTML as it is.
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
在頁面底部只包含此插件文件並編寫以下代碼:
// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();
search.getAjax("http://www.myurl.com/search/", function(rsp){
// Now do whatever you want to with your response
});
或者,如果使用參數化 URL,則使用以下命令:
$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
// Now do work with your response;
})
這是項目的鏈接https://bitbucket.org/ranjeet1985/forminteract
您可以將此插件用於多種用途,例如獲取表單的值、將值放入表單、驗證表單等等。 您可以在項目的 index.html 文件中看到一些代碼示例。
當然我是這個項目的作者,歡迎大家把它做得更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.