junior
junior

Reputation: 808

jquery - how to validate at least one input text is filled

This is my form code

<form action="http://localhost/package/insert" accept-charset="utf-8" name="frmAdd" id="frmAdd" method="POST" enctype="multipart/form-data">
            <input type="radio" name="type" id="type_single" value="single" style="float:left">
            <span style="float:left;margin-right:30px;">Single</span>

            <span id="val-type" class="tooltips">Type is required!</span>

            <input type="text" name="single" id="single" />
            <span id="val-single" class="tooltips">Single is required!</span>
            - OR -
            <input type="file" name="single_list">
            <span id="val-single_list" class="tooltips">Single is required!</span>
    </form>

frmAdd function:

$(document).ready(function() {

  $('#frmAdd').ajaxForm({
    target: "#targetForm",
    type: "POST",
    dataType: "json",
    beforeSubmit: function() {
      return checkForm();
    }
  });
});

and this is my checkForm() function

function checkForm() {
    var flag = true;

    if (!$('input:radio:checked').length > 0) {
        $("#val-type").fadeIn('slow');
        flag = false;
    }

    if ($("#type_single").is(':checked')) {
        var single_val = $("#single").val();
        single_list_val = $("#single_list").val();

        if (single_val == '' && $.trim(single_val == '')) {
            $("#val-single").fadeIn('slow');
            flag = false;
        }
    }    

    if (flag == false) {
        setTimeout(function() {
            $('.tooltips').fadeOut('slow');
        }, 3000);
        return false;
    }

    return true;
}

this part:

<input type="text" name="single" id="single" />
<span id="val-single" class="tooltips">Single is required!</span>
- OR -
<input type="file" name="single_list">
<span id="val-single_list" class="tooltips">Single is required!</span>

how to validate at least if one of those input text is filled the form is valid, I don't want to use any jquery plugins to do this.

Upvotes: 0

Views: 1518

Answers (2)

T J
T J

Reputation: 43156

You can add the following to your validation function:

if (!($('input[name="single"]').val() || $('input[name="single_list"]').val())) {
    flag = false;
}

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You can do this:

if($('input[type=text]').filter(function(){ return $(this).val(); }).length != 0){
  // at least one is filled
}

Upvotes: 1

Related Questions