I have a form to edit a database table that’s populated by setting the <input value="<?php echo $myvalue?>"> however I’m trying to validate the form and if I erase the field, on form_submit, the value returns as the old $myvalue instead of the "" which I would be wanting to see. I notice in the HTML that the value attribute is still set, which makes some sense, but I’m not sure how any forms check if the input is empty in this case!?
This is my validation function so far.. I haven’t been able to test it completely yet.
$(".my-form").submit( function(e) {
$('error-desc').hide();
$('input').removeClass('error');
$('input[name^=edit]').each( function(){
if ($(this).val()===""){
$(this).addClass('error');
$('error-desc').show();
}
});
$('.add > .item').each( function(){
var empty = true;
$(this).find('input').each(function(){
if ($(this).val() !== ""){
empty = false;
}
});
if (!empty){
$(this).find('input[name^=edit][value=""]').each(function(){
$(this).addClass('error');
$('error-desc').show();
});
}
});
if ($('input').hasClass('error')) {
$('html, body').animate({
scrollTop: $('.error-details').offset().top
}, 2000);
return false;
} else {
return false;
}
});
jQuery’s
.val()method should be returning the correct""if the input is emptied by the user or through javascript regardless of what is in the source.If something else is happening instead, you need to provide a jsfiddle with proof as that isn’t how the
.val()method works. If the input is empty,.val()will return an empty string.Demo: http://jsfiddle.net/eW63x/