12

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?

2
  • 2
    Sounds like you might be better going off with a validation plugin rather than looping through the DOM and trying to handroll it. Or, depending on browser compatibility needs, let the browser handle it for you and use a numeric input type. Commented Apr 25, 2012 at 20:03
  • 3
    @Tom. +1 I liked the way you asked the question. asking for a small bit to do a big thing and not asking "do it all for me". nice question! Commented Apr 25, 2012 at 20:10

5 Answers 5

17
$('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
});
Sign up to request clarification or add additional context in comments.

Comments

6
// 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');
    }
});

5 Comments

:input will select <select> elements as well, there is no reason to validate them, it's not "free text"
@gdoron Not just <select> even the buttons
Indeed, :input is probably too vague, but didn't know if we were talking type="text", using HTML5 and type="number" or whatever other variation (this is also why I mentioned the alternate selector in my answer)
instead of var $el = $(this); $el.val() use this: this.value. Don't abuse jQuery, it shouldn't be used instead of javascript native DOM elements.
@gdoron: I did in the second example, but didn't know OPs experience level, and .val() screams simplicity when it comes to input elements. I also doubt they're doing anything in a high-production environment.
2

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>​

5 Comments

I have to ask: You chose to use jQuery for everything but the button binding. Why not $('#theForm input[type="button"]').click(...)? (Or better yet, giving the button an ID and binding to that)
What has your experience, if any, been with $.isNumeric? Better or worse than parseInt, etc.?
You could have done it a lot simpler with [type="text"] in the selector.
@Tom: 6 of 1, half a dozen the other. $.isNumeric validates floating point numbers in addition to integers, that's about the big difference.
@Tom. it's more like parseFloat than parseInt. if decimal values are valid you can use "$.isNumeric" otherwise use parseInt or a regular expression.
1

For each loop:

for (var $input in $('input[type="text"]')) {
    //code here
}

Comments

0

Got this working for me! :) references

Loop through all text boxes in a form using jQuery & https://stackoverflow.com/a/311589

$(document).ready(function() {
		$('form button[type=submit]').click(function() {
			// attach the listener to your button
			debugger;
			var sub_form = $(this.form);
			// use the native JS object with "this"
			$(':input[class="required"]', sub_form).each(function() {
				if (this.value == "") {
					alert("is empty");
				} else {
					alert(this.value);
				}
			});
		});
	});
body {
  margin: 5px;
  padding: 5px;
  border: 1px solid black;
}
#topContainer {
  width: auto;
  margin: 2px;
  padding: 2px;
  border: 1px solid black;
  height: 100px;
}
#mainContainer {
  width: auto;
  height: 200px;
  margin: 2px;
  padding: 2px;
  border: 1px solid black;
}
#footerContainer {
  width: auto;
  height: 200px;
  margin: 2px;
  padding: 2px;
  border: 1px solid black;
}
.gridRow4 {
  margin: 2px 5px;
  width: 25%;
}
.gridRow5 {
  margin: 2px 5px;
  width: ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="topContainer">
    <h2>text goes here
      </h2>
  </div>
  <div id="mainContainer">
    <form id="form1">
      <select id="input1" class="required" name="input1">
        <option value="volvo">Volvo
        </option>
        <option value="saab">Saab
        </option>
        <option value="mercedes">Mercedes
        </option>
        <option value="audi">Audi
        </option>
      </select>
      <select id="input2" class="required" name="input2">
        <option value="Alpha">Alpha
        </option>
        <option value="Beta">Beta
        </option>
        <option value="Gamma">Gamma
        </option>
        <option value="Radial">Radial
        </option>
      </select>
      <select id="input3" class="required" name="input3">
        <option value="">
        </option>
        <option value="up">up
        </option>
        <option value="down">down
        </option>
        <option value="left">left
        </option>
      </select>
      <input id="input4" class="required" type="text" name="input4" />
      <input id="input5" class="required" type="text" name="input5" />
      <select id="input6" class="required" name="input6">
        <option value="1">1
        </option>
        <option value="2">2
        </option>
        <option value="3">3
        </option>
        <option value="4">4
        </option>
      </select>
      <select id="input7" class="required" name="input7">
        <option value="happy">happy
        </option>
        <option value="sad">sad
        </option>
        <option value="round">round
        </option>
        <option value="flat">flat
        </option>
      </select>
      <button id="btn1" name="btn1" type="submit">Submit
      </button>
    </form>
  </div>
  <div id="footerContainer">
    <form id="form2">
      <input id="inputa" class="required" name="inputa">
      <input id="inputb" class="required" name="inputb">
      <input id="inputc" class="required" name="inputc">
      <input id="inputd" class="required" name="inputd">
      <input id="inpute" class="required" name="inpute">
      <input id="inputf" class="required" name="inputf">
      <input id="inputg" class="required" name="inputg">
      <button id="btn2" name="btn2" type="submit">Submit
      </button>
    </form>
  </div>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.