Reputation: 175
I am creating a form with validation. For example I have an input field and submit button that looks like:
<input name="Zip" maxlength="5" id="Zip" value="" />
<a class="form-submit submit-btn" href="javascript:void(0);" style="display: block;">Proceed</a>
Using jQuery, if the input field is empty and they try to submit I want "Zip is Required" to be the new value in RED text inside of the input field.
When the user clicks the field to edit, the red error text will go away and they can type their Zip Code.
I ONLY want the input field to clear onclick when the error message is present. Does this make sense?
This is what I have so far and I'm very new at jQuery. When you click the error message goes away, but when you enter a new zip, click out and click back in, the new zip goes away!
if($('#Zip').val() == ''){
$('#Zip').val('Zip is Required');
$('#Zip').css('color', 'red');
if($('#Zip').val() == 'Zip is Required'){
$('#Zip').click(function() {
$('#Zip').val('');
$('#Zip').css('color', 'black');
});
}
}
Thank you for your help!
Upvotes: 0
Views: 1166
Reputation: 1557
$(document).ready(function() {
///this section clears any text typed inside the box if the user decides to type again
$('#Zip').click(function()
{
if(isNaN(CheckZip))
{
$('#Zip').val('');
}
});
///This section does the security checking to see if the input is empty and add the required text
$('.submit-btn').click(function()
{
var CheckZip = $('#Zip').val();
if(!CheckZip)
{
$('#Zip').val('Zip is Required');
}
});
///Let me know if I`m missing anything
Upvotes: 1
Reputation: 522
Here is how i would do it:
At the onclick event of the input field, you verify if code_required(a boolean variable) is True or False (False by default)
When the user press on the submit button, you verify if the text is empty. If so, you put the variable code_required to True and you write your red message.
When he clicks again, the function will verify if the boolean is True or False and then do the appropriate thing (aka erase the field if necessary). You can then reassign your boolean to False
Upvotes: 0