I have a form which is laid out like a spreadsheet.
I want to validate the text in each textbox and if it's not numeric, change the background of the textbox and display a message.
I can do everything except for the looping part.
I'm guessing it's a for...each statement?
// locate all ":input" elements within a generic <form>,
// then use .each() to loop through all results
$('form :input').each(function(){
var $el = $(this); // element we're testing
// attempt to cast the form's value to a number
var n = parseFloat($el.val());
// check if the conversion passed
if (isNaN(n)){
// $el does not have a number in it
}
});
I think is what you're after. You can also specify input[type="text"]
if you want to be more specific to <input type="text" ... />
Or, more concisely:
$('form input[type="text"]').each(function(i,e){
if (isNaN(parseFloat(e.value,10))){
$(e).css('backgroundColor','red');
}
});
$('form input[type="text"]').each(function(){
// Do your magic here
if (this.value.match(/\D/)) // regular expression for numbers only.
Error();
});
If you got the form id:
$('#formId input[type="text"]').each(function(){
// Do your magic here
});
jsFiddle( http://jsfiddle.net/BctQP/18/ )
<form id="theForm">
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="button" onclick="validateTextBoxes();" value="Click"/>
</form>
<script>
function validateTextBoxes()
{
$("#theForm input").each( function()
{
if ( $(this).is('[type=text]') && !parseInt( $(this).val() ) )
{
$(this).css("background-color","red");
}
});
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With