Home >Web Front-end >Front-end Q&A >How to change element value based on id in jquery
How to change the value of jquery based on id: 1. Set the id attribute to the element; 2. Use the "$("#id attribute value")" statement to obtain the specified element object; 3. Use "element object.html ("new value")", "element object.text("new value")" or "element.val("new value")" statement to modify the element value.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery changes element value based on id
Implementation steps:
Set the id attribute for the specified element
Use the "$("#id attribute value")" statement to obtain the specified element object
Use jquery Method to modify the value of the specified element
There are three methods to modify the element value:
Use text() to set the text content of the selected element .
Use html() to set the content of the selected element (innerHTML).
Use val() to set the value of the input element
Example 1: Use text()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("#xg").text("Hello world!"); }); }); </script> </head> <body> <button>修改id="xg"的p元素的文本内容</button> <p id="xg">这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
Example 2: Using html()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("#xg").html("Hello <b>world!</b>"); }); }); </script> </head> <body> <button>修改id="xg"的p元素的文本内容</button> <p id="xg">这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
Example 3: Using val()
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("#name").val("Hello m.sbmmt.com"); }); }); </script> </head> <body> <button>修改id="name"的input元素的文本内容</button><br><br> 用户名: <input id="name" type="text" name="user" value="Hello" /> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to change element value based on id in jquery. For more information, please follow other related articles on the PHP Chinese website!