Required and Readonly using jQuery


Demo Download

There are several situations in web development when we need to user both html attribute together which are required and readonly. But if you look them carefully then you can say that logically if field is required then it can not be readonly because user can not type here if we make it readonly. Therefore these both does not work together.

Solution of this problem is through jQuery, today i will share a tutorial how to implement required and readonly using jQuery. I will use a simple calendar tutorial where we insert date into field through calendar, because we want user to insert data in our specified format therefore we make field readonly through jQuery.

Libraries

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<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>

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: "both",
buttonImage: "b_calendar.png",
buttonImageOnly: true,
buttonText: "Select date",
changeMonth: true,
changeYear: true,
yearRange: "-100:+0"
});
});

Demo Download

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

Leave a Reply

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