Amit
Amit

Reputation: 7035

jquery dynamic validation based on selection

I have below jquery code where I loop through a div and find 2 dropdowns and 1 text box.

So basically each row in the div will have 2 HTML SELECT and 1 input type text box

I want to put validation on the text box based on the selected value of these 2 HTML select.

So for ex: if I select option1 from 1st dropdown and elect option3 from 2nd dropdown then my textbox can only take 20 characters.

Please advice how can I do this.

var searchString = '';
        $("#btnSearch").click(function () {
            searchString = "";
            $("div.cloneRow").each(function () {
                if ($(this).find("input[type=text]").val() != '') {
                    $(this).find("select").each(function () {
                        if ($.trim($(this).val()) != '') {
                            searchString += $.trim($(this).val()) + " ";
                        }
                    });
                    $(this).find("input[type=text]").each(function () {
                        searchString += $.trim($(this).val());
                    });
                }
            });
            alert(searchString);
        });
    });

Thanks

Upvotes: 1

Views: 931

Answers (1)

omerkirk
omerkirk

Reputation: 2527

Every time you press the button you loop over your divs that contain the 2 selectboxes and a textbox and for each textbox you check the values for the select boxes and make a decision. I gave an example case but it can be further improved. Hope it helps

          $("#yourbuttonid").click(function(){
              $("div.cloneRow").each(function () {
                  var $select1 = $($(this).find("select.first"));
                  var $select2 = $($(this).find("select.second"));
                  var $text = $("input[type='text']");
                  if($select2.val() != ""){
                      //Your cases go in here
                      if($select1.val() == "1" && $select2.val() == "4"){
                          //check if the allowed length is exceeded for this case
                          if($text.val().length > 20){
                              //if it is empty the textbox and give a red border
                              $text.val("");
                              $text.css("border", "1px solid red");
                          }
                      }
                      //other cases go here
                  } 
              });
          });

Upvotes: 1

Related Questions