Prevent submission of a field with the default value
i am using the rails 3 UJS for my forms.
开发者_StackOverflowIn one of the fields, i have the default value as "ABC".
If the user did not change the field, I do not want this value to be submitted.
1) It is an optional field, so i do not want to prevent the form from submitting
2) I could hijack the ":before" action, but that seems hackish to me
This seems like a common use case - what is the most elegant way of doing this?
If you only want to support HTML5-aware browsers, you can use the placeholder
attribute of the <input>
tag instead of setting a value you don't want to submit.
<input type="text" placeholder="ABC" />
Bear in mind that IE9 does not support this attribute (source).
If you'd rather not, you could use the form's submit
event to clear the form field if it hasn't been changed.
$("#my-form").submit(function(event) {
var input = $("#my-input-box");
if (input.val() === "ABC") {
input.val("");
}
});
You may find that your users sometimes want to type "ABC" into the box. You can solve this by setting a flag when the contents are changed and checking whether the flag is set in the above code instead of comparing the current value to the default.
精彩评论