[英]How can I set the input value of a form in javascript?
假設我定義了一個表單 ( my_form
),它有一個名為myInput
的輸入。 我想將myInput
的值設置為my_string
。
$('#my_form textarea[name=myInput]').value = my_string;
我已經嘗試了上面的行,這適用於大多數瀏覽器,但不適用於 Opera/Safari。 我知道它不適用於 Opera/Safari,因為這條線
console.log($('#my_form textarea[name=myInput]').value + " was the string");
logs undefined was the string
屏幕上undefined was the string
,而不是 my_string 的實際值(不是 undefined)。
我怎樣才能為這些瀏覽器實現這一點?
試試這個例子:
$(document).ready(function () { $("#btn1").click(function () { $("#test1").text("Hello world!"); }); $("#btn2").click(function () { $("#test2").html("<b>Hello world!</b>"); }); $("#btn3").click(function () { $("#test3").val("Dolly Duck"); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id="test1">This is a paragraph.</p> <p id="test2">This is another paragraph.</p> <p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p> <button id="btn1">Set Text</button> <button id="btn2">Set HTML</button> <button id="btn3">Set Value</button>
您必須使用.val()而不是.value
。 和字符串的引號。
所以最終的代碼將是:
$("#my_form textarea[name=myInput]").val("my_string_with_quotes_before_and_after");
或帶有變量
var string="some text";
$("#my_form textarea[name=myInput]").val(string);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.