Required and Readonly using jQuery

Sometimes we need to make field readonly along with required attribute but unfortunately, readonly and required do not work together just because if field is required than it can not be readonly so user must need to enter data in it. I was also stuck in a problem of using them together when i was using jQuery DatePicker with required format and i don’t want user to type value but just click on icon and select date as per required format. Below code can help you to achieve it.

Demo: https://jsfiddle.net/javedfiddle/LbyL4ar9/

HTML

<form action="" method="">
<input type="text" name="date" class="date readonly" placeholder="DD/MM/YYYY" required /><br /><br />
<input type="submit" value="Submit" />
</form>

JQuery

// To make field readonly
$(".readonly").keydown(function(e){
e.preventDefault();
});

// To user jQuery DatePicker
$(function() {
$( ".date" ).datepicker({
dateFormat : 'dd/mm/yy',
showOn: "button",
buttonImage: "https://htmlcssphptutorial.files.wordpress.com/2015/09/b_calendar.png",
buttonImageOnly: true,
buttonText: "Select date"
});
});

Complete Code

<html>
<head>
<title>Required and Readonly using jQuery</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<form action="" method="">
<input type="text" name="date" class="date readonly" placeholder="DD/MM/YYYY" required /><br /><br />
<input type="submit" value="Submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
// To make field readonly
$(".readonly").keydown(function(e){
e.preventDefault();
});

// To user jQuery DatePicker
$(function() {
$( ".date" ).datepicker({
dateFormat : 'dd/mm/yy',
showOn: "button",
buttonImage: "https://htmlcssphptutorial.files.wordpress.com/2015/09/b_calendar.png",
buttonImageOnly: true,
buttonText: "Select date"
});
});
</script>
</body>
</html>

Demo: https://jsfiddle.net/javedfiddle/LbyL4ar9/

Leave your comments and share this tutorial with your friends, if you find this tutorial helpful. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s