27 Jan jQuery – Set Content
To set the content on a web page using jQuery, we can use the text(), html() and val() methods. In this lesson, we will learn how to,
- Set the Text of the selected element
- Set the Content of the Form Fields
Set the Text of the selected element
To set the text of the selected element in jQuery, use the text() and html() methods. Let us see an example wherein we will set the text of the <p> element:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").text("This is demo text!"); }); $("#btn2").click(function(){ $("p").text("This is <em>demo</em> <strong>text</strong>!"); }); }); </script> <style> p { background: black; color: white; font-size: 22px; } button { background: red; color: white; font-size: 30px; text-align: center; padding: 15px; } </style> </head> <body> <h1>Demo Heading</h1> <p>Click the below buttons to set text and html.</p> <button id="btn1">Set Text</button> <button id="btn2">Set HTML</button> </body> </html> |
Set the Content of the Form Fields
To set the content of the Form fields, use the val() method in jQuery. Let us see another example wherein we will set the content to 3 form fields:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("#ename").val("Amit Thinks"); }); $("#btn2").click(function(){ $("#edept").val("Tech"); }); $("#btn3").click(function(){ $("#ezone").val("North"); }); }); </script> <style> button { background: red; color: white; font-size: 15px; text-align: center; padding: 15px; } </style> </head> <body> <h1>Employee Details</h1> <p>Employee Name: <input type="text" id="ename" value=""/></p> <p>Employee Department: <input type="text" id="edept" value=""/></p> <p>Employee Zone: <input type="text" id="ezone" value=""/></p> <button id="btn1">Set the Employee Name</button> <button id="btn2">Set the Employee Department</button> <button id="btn3">Set the Employee Zone</button> </body> </html> |
Output
No Comments