用jQuery來修改input元素的value屬性值


假設我們如下給出的輸入型別和“John Smith”的值 −

<input type = 'text' value = 'John Smith' id = 'changeTheName' />

使用attr()方法對其進行修改 −

$('#changeTheName').attr('value', 'Please enter your name.......');

您需要使用attr()的概念。以下是程式碼 −

例項

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input type = 'text' value = 'John Smith' id = 'changeTheName' />
<script>
   $('#changeTheName').attr('value', 'Please enter your name.......');
</script>
</body>
</html>

要執行上述程式,請儲存檔名“anyName.html(index.html)”並右鍵單擊該檔案。在VS Code編輯器中選擇選項“使用Live Server開啟”。

輸出

這將產生以下輸出 −

更新於: 10-9-2020

5K+ 瀏覽

啟動您的職業生涯

完成課程後取得認證

開始
廣告
© . All rights reserved.