I need a function that when I click on the textbox if it is empty it gets a color, and if filled change the color, but only when I click on it, how can I do it? If you have not filled in I will call this function:
function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
And if you have, I'll call this:
function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
Edition: I have this field in the modal, for example:
<div class="input-group">
<asp:TextBox ID="txtHora" runat="server" class="form-control" onblur="Verifica_Hora(this);"></asp:TextBox>
<span class="input-group-addon danger"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
I already have the function that works if I put required:
$(document).ready(function() {
$('.input-group input[required], .input-group textarea[required], .input-group select[required]').on('keyup change', function() {
var $form = $(this).closest('form'),
$group = $(this).closest('.input-group'),
$addon = $group.find('.input-group-addon'),
$icon = $addon.find('span'),
state = false;
if (!$group.data('validate')) {
state = $(this).val() ? true : false;
} else if ($group.data('validate') == "email") {
state = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($(this).val())
} else if ($group.data('validate') == 'phone') {
state = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/.test($(this).val())
} else if ($group.data('validate') == "length") {
state = $(this).val().length >= $group.data('length') ? true : false;
} else if ($group.data('validate') == "number") {
state = !isNaN(parseFloat($(this).val())) && isFinite($(this).val());
}
if (state) {
$addon.removeClass('danger');
$addon.addClass('success');
$icon.attr('class', 'glyphicon glyphicon-ok');
} else {
$addon.removeClass('success');
$addon.addClass('danger');
$icon.attr('class', 'glyphicon glyphicon-asterisk');
}
});
$('.input-group input[required], .input-group textarea[required],
.input-group select[required]').trigger('change');
});
If it is populated, it changes the image of the asterisk to ok. And this, change the textbox from red to normal, if something is typed:
$(document).ready(function() {
$('#contact-form').validate({
rules: {
txtNome: {
minlength: 2,
required: true
}
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
Only these two only work out of the modal. Then in the modal I need to check the fields, when clicked, and when something is typed. I did not get to make the modal work with required, as if I put required, I can not open the modal with the click of the button.