Reset HTML5 invalid input state
The inputs with a validation are initially not marked as invalid until the value changes. How do I restore this initial state?
My problem in detail: I have a simple order form. If the user clicks the "add item" button, I clone the first item and empty the input fields. But since I'm using html5 validation, the emptying makes them invalid.
This is what happens after clicking "Add Product", even if the first set of fields is valid:
Demo: http://jsfiddle.net/WEHdp/ (view in Firefox):
<form action="/orders/preview" method="post">
<div class="orderData">
<input name="order[order_items_attributes][0][articleno]" pattern="[0-9]{4}" required /> /
<input name="order[order_items_attributes][0][colorno]" pattern="[0-9]{3}" required />
<div>
<a href="#" class="removeOrder">Remove product</a>
<a href="#" class="addOrder">Add product</a>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script>
$(document).ready(func开发者_StackOverflow社区tion() {
$(".addOrder").live("click", function (event) {
event.preventDefault();
// Clone div
$('.orderData:first').clone().insertAfter(".orderData:last");
// Empty the fields
$('.orderData:last input').val("");
});
$(".removeOrder").live("click", function (event) {
event.preventDefault();
if($('.orderData').size() > 1){
$(this).parents('.orderData').remove();
}
});
});
</script>
Clone the row on page ready, then you will always have a reference to the row in its default state.
Like so:
$(document).ready(function() {
var firstCopy = $('.orderData:first').clone();
$(".addOrder").live("click", function (event) {
event.preventDefault();
// Clone div
firstCopy.clone().insertAfter(".orderData:last");
// Empty the fields
$('.orderData:last input').val("");
});
$(".removeOrder").live("click", function (event) {
event.preventDefault();
if($('.orderData').size() > 1){
$(this).parents('.orderData').remove();
}
});
});
Html 5 validation marks the field as invalid because you have a required
attribute on them.
Strip that and the marking will disappear when the field is empty. This is because empty states are valid for non-required fields, while it renders reqiured fields invalid (hence the marking).
No need for hacks. Just logic :)
精彩评论