2

I am a jQuery/JavaScript beginner and trying to create a spreadsheet-style form with validation so that, once information has been entered for any field in the row, all fields in that row should be required too. This post and one of the suggestions posted there were extremely helpful in terms of how to handle validation of text input fields in the row. However, I also need to apply that validation logic to select fields in the row as well. I've tried changing the settings in the .on() and .find() functions, but am having no luck. How could this script (taken from the post above) be changed to handle the select fields in the row as well as the text input fields? Here is a demo with the row validation working for the text inputs, but not the select fields. Thank you!

$("#mytable").on("input", "input", function(){
    var anySet = false,
        $cells = $(this).closest("tr").find("td input");
    $cells.each(function() {
        var somethingInCell = $(this).val().trim() !== '';
        anySet |= somethingInCell;
    });
    $cells.removeClass("has-error");
    if (anySet) {
        $cells.each(function() {
            if ($(this).val().trim() === '') {
                $(this).addClass("has-error");
            }
        });
    }
});

3 Answers 3

4

how about something like this?

you were nearly there, just needed a way to target select fields and find out how they trigger events - .change(). once you have that, you can find the .val() of the selects and compare it to NA (the equivalent of empty/null/not selected) and then add has-error accordingly.

$(document).ready(function() {
    $("#mytable").on("change", "input, select", function(){    
        var $selects = $(this).closest('tr').find('td select'),
            $cells = $(this).closest("tr").find("td input");
        $cells.removeClass("has-error");
        $selects.removeClass("has-error");
        $cells.each(function() {
            if ($(this).val().trim() === '') {
                $(this).addClass("has-error");
            }
        });
        $selects.each(function() {
            console.log($(this).val() == 'NA');
            if ($(this).val() == 'NA') {
                $(this).addClass("has-error");
            }
        });
    });
});
.has-error{
    
border-style: solid;
    border-color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<table id="mytable">
    <tr>
        <th>Row</th>
        <th>ID</th>
        <th>Date</th>
        <th>Yes/No</th>
    </tr>
    <tr>
        <td>1</td>
        <td>
            <input type="TEXT" id="ID1" name="ID1" class="target ids" />
        </td>
        <td>
            <input type="TEXT" id="DATE1" name="DATE1" class="target"  />
        </td>
        <td>
            <select id="YN1" name="YN1" class="target" >
                <option value="NA">NA</option>
                <option value="Yes">Yes</option>
                <option value="No">No</option>
            </select>
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>
            <input type="TEXT" id="ID2" name="ID2" class="target ids" />
        </td>
        <td>
            <input type="TEXT" id="DATE2" name="DATE2" class="target" />
        </td>
        <td>
            <select id="YN2" name="YN2" class="target" >
                <option value="NA">NA</option>
                <option value="Yes">Yes</option>
                <option value="No">No</option>
            </select>
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>
            <input type="TEXT" id="ID3" name="ID3" class="target ids" />
        </td>
        <td>
            <input type="TEXT" id="DATE3" name="DATE3" class="target"  />
        </td>
        <td>
            <select id="YN3" name="YN3" class="target" >
                <option value="NA">NA</option>
                <option value="Yes">Yes</option>
                <option value="No">No</option>
            </select>
        </td>
    </tr>
</table>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This is exactly what I was looking for, much appreciated!
0

I played with your code a bit and got the desired result. I thought it would be better to target the .target class rather than trying to target both input and select.

The other problem you have is that, even though the select option has no value, the value that gets sent defaults to the value in between the option tags. So we need to verify against that value as well.

// Listen for input and change events (input = input select = change)
// Target element by classname rather than label
$("#mytable").on("input, change", "td .target", function () {
    var anySet = false,
        $cells = $(this).closest("tr").find("td .target");
    $cells.each(function () {

        // Get the value of input/select
        var somethingInCell = $(this).val().trim();
        console.log(somethingInCell)

        if (somethingInCell === '' || somethingInCell === 'NA') {

          // Using anySet var to run validation
          anySet = true
        }

        //anySet |= somethingInCell;
    });
    $cells.removeClass("has-error");
    if (anySet) {
        $cells.each(function () {
            if ($(this).val().trim() === '' || $(this).val().trim() === 'NA') {
                $(this).addClass("has-error");
            }
        });
    }
});

Fiddle here JSFiddle

This can be cleaned up quite a bit but I'm just answering your initial question. Hopefully you can understand a bit more about this and use it to help.

2 Comments

Thank you very much for taking the time. The answer below behaves exactly the way I need. Your suggestion is almost perfect, but I found that if I enter information in the fields out of the expected order (for example, enter something in 'Date' before in 'ID'), the logic is not being applied the way I would expect. Thanks again.
Glad you found your solution
-3

Validation can be a tricky thing - it can be very complicated, thankfully, we live in a world we have access to the Internet, a place where people do amazing things and share those things for free.

Check out: http://jqueryvalidation.org/

A free plugin for validation, small, and easy to use.

Basic Example:

<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
  <legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
  <label for="cname">Name (required, at least 2 characters)</label>
  <input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
  <label for="cemail">E-Mail (required)</label>
  <input id="cemail" type="email" name="email" required>
</p>
<p>
  <label for="curl">URL (optional)</label>
  <input id="curl" type="url" name="url">
</p>
<p>
  <label for="ccomment">Your comment (required)</label>
  <textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
  <input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
   $("#commentForm").validate();
</script>

2 Comments

^ haha this guy. Not condescending - literally, thankful for what people do and give for free. As a coworker of mine says "I don't know how people programmed before the Internet." Also, please leave something that is constructive. Everyone has their own way of learning, if you think something is better, provide it.
The question wasn't "which jQuery validation plugin should I use"

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.