Looping through fields to validate with jQuery

Is there a way to do this with jQuery?

Here is setup:

<input type='checkbox' class='sk1' />   <input type='text' class='skill1' />
<input type='checkbox' class='sk2' />   <input type='text' class='skill2' />
<input type='checkbox' class='sk3' />   <input type='text' class='skill3' />

<input type="button" onclick="validate();" />

Important: The input field to the right of checkbox is associated with checkbox.

When button is clicked, I want this check: Each checkbox that is checked, can not have an empty input field to the right of it. When it finds one, it will stop and throw an alert.

Looking around, I see I will need to probably uses regex and perhaps the jQuery.each.

Pseudo code:

for each checkbox class^=sk[number]
    check if input[type=text] that has a class with skill[same number as above]
    if empty, alert,
       Otherwise, continue checking other boxes

(Sidenote: Writing that pseudo makes me wonder if there is a better naming convention I can use so that I don't have to extract specific numbers out of these.)

(another note: When an checkbox is NOT checked, the text field is disabled; I have this working)

Can someone give me some guidence on this?


Just loop the checkboxes and check the next text element:

$(":checkbox:checked").each(function() {
    if (!$(this).next(":text").val().length) {
        alert("You must put in text!");
        return false; //bail out of the loop, return true to skip to the next iteration

Demo: http://jsfiddle.net/uvQ6C/

Need Your Help

Running a PHP script inside a Python WSGI enviroment

php python django apache wsgi

I have a simple PHP script that outputs a dir listing in XML format. I use it to let a flash slideshow know what files are available to show.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.