[英]getting the value of a textbox when user enters the name/id of the field
使用jquery獲取文本框的值。
但
我需要輸入文本框的ID,然后使用該值通過jquery獲取文本框的值。
var tt = $("#fieldname").val()
這樣可行
現在如何在運行時輸入字段名稱,並讓jquery像執行硬編碼一樣執行val命令?
有幾種方法可以做到這一點。 一種方法是偵聽鍵盤之一或在輸入ID的文本框中更改事件,以幫助確定何時更改了輸入。 所以舉個例子
$("#inputText").on("keyup", function(keyupEvent){ var textboxId = $("#inputText").val(); var textboxIdValue = $("#" + textboxId).val(); });
或者另一種方式是使用具有類似邏輯的click事件,例如
$("#clickMe").on("click", function(){ var textboxId = $("#inputText").val(); var textboxIdValue = $("#" + textboxId).val(); })
兩者的用例示例可以在這里https://fiddle.jshell.net/xpvt214o/114584/
這是您入門的示例:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
以及相應的jQuery代碼:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
這將顯示指定輸入的值(如果存在)。
您可以在此處查看它的運行情況: https : //jsfiddle.net/jeevantakhar/xpvt214o/114558/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.