How to add attributes to an HTML element using jQuery

Complete Program for adding required attribute, and setting some value in html element using jquery

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Adding Attribute to HTML Element Using jQuery</title>
	<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
	<script>
		$(document).ready(function(){
			$(".add-attribute").click(function(){  
				// Setting Checkbox is checked
				$('input[type="checkbox"]').attr("checked", "checked"); 
				// Setting a test value in textbox
				$('input[type="text"]').attr("value", "My Name is Shailendra"); 
			});
		});
	</script> 
</head>
<body>
    <h3>Adding Attribute to HTML Element Using jQuery</h3>
    <input type="checkbox"> <br/>
	<input type="text"> <br/><br/>
	<button type="button" class="add-attribute">Click Action</button>
</body>
</html> 

Example 1:

// Adding Required Attribute to #first_name 
$('#first_name').attr('required', 'required');

// Removing Required Attribute from #first_name 
$('#first_name').removeAttr('required');  

Example 2:

Example 2:
// Adding Required Attribute to #first_name 
$('#first_name').prop('required', true);

// Removing Required Attribute from #first_name 
$('#first_name').prop('required', false);

One thought on “How to add attributes to an HTML element using jQuery

  • AffiliateLabz
    February 22, 2020 at 12:32 am

    Great content! Super high-quality! Keep it up! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>