Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all text boxes in a form using jQuery

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?

like image 314
Tom Avatar asked Apr 25 '12 20:04

Tom


3 Answers

// 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');
    }
});
like image 151
Brad Christie Avatar answered Oct 21 '22 15:10

Brad Christie


$('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
});
like image 27
gdoron is supporting Monica Avatar answered Oct 21 '22 13:10

gdoron is supporting Monica


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>​
like image 20
Jonathan Payne Avatar answered Oct 21 '22 13:10

Jonathan Payne