验证所有文本输入中是否包含值,并且没有相同的

时间:2015-04-27 12:47:12

标签: jquery

我有以下代码可以检查其他值以确保没有相同但我怎样才能验证每个文本输入中都有一个值:

$( "#save_sort_order_board_members" ).click(function(e) {
    $('#sort_error_text').html('');
    var failed;
    var inputs = {};
      $('.sort_member_order_text').each(function() {
        if (inputs[this.value] !== undefined) {
          // a previous element with the same value exists
          // apply class to both elements
          //$([this, inputs[this.value]]).addClass('same');
          $('#sort_error_text').html('You need to have different values to sumbit!');
          failed = "yes";
        }
        inputs[this.value] = this;
      });
      if(failed!="yes"){
        $('#sort_board_member_field_values').submit();
      }
});

这是一个JS小提琴:http://jsfiddle.net/0o1ze3wu/

3 个答案:

答案 0 :(得分:1)

您需要trim值:

  

从字符串的开头和结尾删除空格。

$(document).ready(function () {
    $("#save_sort_order_board_members").click(function (e) {
        $('#sort_error_text').html('');

        var failed;
        var inputs = {};
        $('#sort_board_member_field_values input[type="text"]').each(function () {
            var thisVal = $.trim($(this).val());
            if (!thisVal) {
                alert('All fields are compulsory');
                failed = true;
            } else if (inputs[thisVal]) {
                alert('All inputs should have different values');
                failed = true;
            }
            inputs[thisVal] = true;
        });

        if (failed) {
            return false;
        }
        $('#sort_board_member_field_values').submit();
    });
});

文档:http://api.jquery.com/jQuery.trim/

演示:http://jsfiddle.net/0o1ze3wu/2/

答案 1 :(得分:0)

您可以使用:

Android Studio

答案 2 :(得分:0)

在@Tushar的帮助下,我能够解决它:

$( "#save_sort_order_board_members" ).click(function(e) {
    $('#sort_error_text').html('');
    var failed;
    var inputs = {};
    $('.sort_member_order_text').each(function () {
        if ($.trim($(this).val())==='' || inputs[this.value] !== undefined) {
            $('#sort_error_text').html('You need to have different values to sumbit!');
            failed = "yes";
            alert('failed');
        }
        inputs[this.value] = this;
    });
    if (failed != "yes") {
        alert('success');
        return false;
        $('#sort_board_member_field_values').submit();
    }
});