【问题标题】:Textfield and dropdown validation for dynamic HTML ids using jquery使用 jquery 对动态 HTML id 进行文本字段和下拉验证
【发布时间】:2023-04-03 07:24:01
【问题描述】:

我正在尝试以组合状态验证下拉列表和文本文件。两者都可以为空,或者都必须填写。 html id 是动态生成的。我尝试使用以下代码,但它不起作用。我已使用以下链接进行实施。 http://jsfiddle.net/BE5Lr/4097/

how to validate html elements with dynamic id

HTML

<!-- VALUE -->
<!-- Text field -->
<div class="col-md-3" ng-if="property.dataTypeId === 3 ">
    <input id="{{property.propertyId}}Value" name="QtePack" type="text"  class="form-control" ng-model="property.propertyValues[0].label">
</div>

<!-- Date -->
<div class="col-md-offset-2 col-md-1" ng-if="property.dataTypeId === 4 ">
    <datepicker date-format="dd/MM"> <input id="{{property.propertyId}}yearEnd" name="PackType" type="text" class="form-control" ng-model="property.propertyValues[0].label"> </datepicker>
</div>

<div ng-if="formName == 'CREATE' ">
    <input type="submit" value="Add" ng-click="add()" ng-disabled="entityAddForm.$invalid" class="btn btn-primary">
    <button type="reset" class="btn btn-primary">Reset</button>
</div>

jquery

$("input[name='QtePack']").each(function(){
    var ip = $(this);
    var sel = $(this).closest("tr").find("input[name='PackType']");

    if((ip.val().length==0 && sel.val().length!=0) || (ip.val().length!=0 && sel.val().length==0))
    {
        //alert('enter both type and quant or leave both blank');
        valid = false;
        ip.addClass('error');
        sel.addClass('error');
    }
    else{     
        ip.removeClass('error');
        sel.removeClass('error');
    }
});

【问题讨论】:

  • 你为什么不使用角度验证顺便说一句。它们很容易实现并且是声明性的

标签: jquery html angularjs


【解决方案1】:

您想验证最后的输入/选择吗?

我认为它有效:

var a = {
    Products: [{
        "ProductType": "Hexagon bolt",
            "ProductID": "#1987|58x34|Polyamid PA6"
    }, {
        "ProductType": "Star bolt",
            "ProductID": "#1268|109x74|Polyamid PA6"
    }, {
        "ProductType": "Plan bolt",
            "ProductID": "#1077|46x82|Polyamid PA6G"
    }, {
        "ProductType": "Flat bolt",
            "ProductID": "#1717|46x82|Polyamid PA6G"
    }, {
        "ProductType": "AGA bolt",
            "ProductID": "#1812|30x18|Polyamid PA6"
    }, {
        "ProductType": "W40 bolt",
            "ProductID": "#6190|100x16|Polyamid PA6"
    }]
};

$.each(a.Products, function (key, value) {
    $("#Produkt_").append($('<option></option>').val(value.ProductID).html(value.ProductType));
});

// Add button
var counter = 1;
$("#AddButton").click(function () {
    var $clone = $('#AddFieldsToFormDiv tr.cloneme:first').clone(true);

    if (counter > 3) {
        alert('No more rows to add.');
        return false;
    }

    $clone.find("input, select").val('').removeClass('error').each(function () {

        $(this).attr({
            'id': function (_, id) {
                return id + counter
            },
            //'name': function(_, name) { return name + counter },
            'value': ''
        });

    }).end().appendTo("#AddFieldsToFormDiv");
    $clone.append("<td><input type='button' value='Delete' id='DeleteButton'></td>");
    counter++;

});

// Remove rows from table
$('#AddFieldsToFormDiv').on('click', '#DeleteButton', function () {
    $(this).closest('tr').remove();
    counter--;
});



function sortDropDownListByText() {

    $("select").each(function () {

        var selectedValue = $(this).val();

        $(this).html($("option", $(this)).sort(function (a, b) {
            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));

        $(this).val(selectedValue);
    });
}

sortDropDownListByText();



// Split and add dropdown value to inputs
$(document).on('change', '[id^="Produkt_"]', function () {
    SplitSelectValue($(this));
});

function SplitSelectValue(obj) {
    var data = obj.find("option:selected").val();
    var arr = data.split('|');
    var tr = obj.closest('tr');
    tr.find("[id^='SelVala_']").val(arr[0]);
    tr.find("[id^='SelValb_']").val(arr[1]);
    tr.find("[id^='SelValc_']").val(arr[2]);
}

$('#SendButton').click(function (e) {
    // Validate if empty
    var valid = true;
    $('.required').each(function () {
        var $this = $(this);
        if ($.trim($(this).val()) == '') {
            valid = false;
            $(this).addClass('error');
        } else {
            $(this).removeClass('error');
        }
    });

   
    $("input[name='QtePack']").each(function(){
        var ip = $(this);
        var sel =      $(this).parent().parent().find("select[name='PackType']");
       
        if((ip.val().length==0 && sel.val().length!=0) || 
           (ip.val().length!=0 && sel.val().length==0)) {
                 //alert('enter both type and quant or leave both blank');
            valid = false;
                 ip.addClass('error');
            sel.addClass('error');
        }
        else{     
            ip.removeClass('error');
            sel.removeClass('error');
        }
    });
    

    // Show validation alert
    if (valid == false) {
        e.preventDefault();
        alert('Some field(s) is required.');

        return false;
    }

});
.error {
    background-color: #FFE1E1;
    border: 1px dashed red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="AddFieldsToFormDiv" border="1">
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
    <tr class="cloneme">
        <td>
            <input type="text" id="SelVala_" size="6" disabled readonly>
        </td>
        <td>
            <input type="text" id="SelValb_" size="6" disabled readonly>
        </td>
        <td>
            <input type="text" id="SelValc_" size="16" disabled readonly>
        </td>
        <td>
            <select id="Produkt_" name="Produkt" style="width:130px" class="required">
                <option value=""></option>
            </select>
        </td>
        <td>
            <input type="text" id="Qte_Pack_" name="QtePack" size="6">
        </td>
        <td>
            <select id="Pack_Type_" name="PackType" style="width:80px">
                <option value=""></option>
                <option value="B8">B8</option>
                <option value="B5">B5</option>
            </select>
        </td>
    </tr>
</table>
<input type="button" id="AddButton" value="Add">&nbsp;&nbsp;
<input type="button" id="SendButton" value="Send">

【讨论】:

  • 我想验证 2 个输入字段。
  • 点击发送时,验证第 4 列是否有值,第 5 列和第 6 列是空还是满,对吧?
  • 到目前为止,我只关心第 5 列和第 6 列是空的还是满的
  • 我正在比较两个输入文本字段。我想我需要重构这一行以匹配我的输入文本字段。 var sel = $(this).parent().parent().find("select[name='PackType']");
  • 您需要重构的输入文本字段是什么?我不明白
【解决方案2】:

这是你要问的吗?请检查小提琴:

Updated JSfiddle

var a = {
  Products: [{
    "ProductType": "Hexagon bolt",
    "ProductID": "#1987|58x34|Polyamid PA6"
  }, {
    "ProductType": "Star bolt",
    "ProductID": "#1268|109x74|Polyamid PA6"
  }, {
    "ProductType": "Plan bolt",
    "ProductID": "#1077|46x82|Polyamid PA6G"
  }, {
    "ProductType": "Flat bolt",
    "ProductID": "#1717|46x82|Polyamid PA6G"
  }, {
    "ProductType": "AGA bolt",
    "ProductID": "#1812|30x18|Polyamid PA6"
  }, {
    "ProductType": "W40 bolt",
    "ProductID": "#6190|100x16|Polyamid PA6"
  }]
};

$.each(a.Products, function(key, value) {
  $("#Produkt_").append($('<option></option>').val(value.ProductID).html(value.ProductType));
});

// Add button
var counter = 1;
$("#AddButton").click(function() {
  var $clone = $('#AddFieldsToFormDiv tr.cloneme:first').clone(true);

  if (counter > 3) {
    alert('No more rows to add.');
    return false;
  }

  $clone.find("input, select").val('').removeClass('error').each(function() {

    $(this).attr({
      'id': function(_, id) {
        return id + counter
      },
      //'name': function(_, name) { return name + counter },
      'value': ''
    });

  }).end().appendTo("#AddFieldsToFormDiv");
  $clone.append("<td><input type='button' value='Delete' id='DeleteButton'></td>");
  counter++;

});

// Remove rows from table
$('#AddFieldsToFormDiv').on('click', '#DeleteButton', function() {
  $(this).closest('tr').remove();
  counter--;
});



function sortDropDownListByText() {

  $("select").each(function() {

    var selectedValue = $(this).val();

    $(this).html($("option", $(this)).sort(function(a, b) {
      return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }));

    $(this).val(selectedValue);
  });
}

sortDropDownListByText();



// Split and add dropdown value to inputs
$(document).on('change', '[id^="Produkt_"]', function() {
  SplitSelectValue($(this));
});

function SplitSelectValue(obj) {
  var data = obj.find("option:selected").val();
  var arr = data.split('|');
  var tr = obj.closest('tr');
  tr.find("[id^='SelVala_']").val(arr[0]);
  tr.find("[id^='SelValb_']").val(arr[1]);
  tr.find("[id^='SelValc_']").val(arr[2]);
}

$('#SendButton').click(function(e) {
  // Validate if empty
  var valid = true;
  $('.drpdwnclass').each(function() {
    var $this = $(this);
    var drp_id = this.id;
    var row_number = drp_id.substring(drp_id.indexOf("_") + 1, drp_id.length);

    if ($.trim($(this).val()) == '' && $.trim($("#Qte_Pack_" + row_number).val()) != '') {
      valid = false;
      $(this).addClass('error');
      $("#Qte_Pack_" + row_number).removeClass('error');
    } else if ($.trim($(this).val()) != '' && $.trim($("#Qte_Pack_" + row_number).val()) == '') {
      valid = false;

      $("#Qte_Pack_" + row_number).addClass('error');
      $(this).removeClass('error');
    } else {
      $(this).removeClass('error');
      $("#Qte_Pack_" + row_number).removeClass('error');
    }
  });


  // Show validation alert
  if (valid == false) {
    e.preventDefault();
    alert('Some field(s) is required.');

    return false;
  }

});
.error {
  background-color: #FFE1E1;
  border: 1px dashed red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="AddFieldsToFormDiv" border="1">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr class="cloneme">
    <td>
      <input type="text" id="SelVala_" size="6" disabled readonly>
    </td>
    <td>
      <input type="text" id="SelValb_" size="6" disabled readonly>
    </td>
    <td>
      <input type="text" id="SelValc_" size="16" disabled readonly>
    </td>
    <td>
      <select id="Produkt_" name="Produkt" style="width:130px" class="required drpdwnclass">
        <option value=""></option>
      </select>
    </td>
    <td>
      <input type="text" id="Qte_Pack_" name="QtePack" size="6">
    </td>
    <td>
      <select id="Pack_Type_" name="PackType" style="width:80px">
        <option value=""></option>
        <option value="B8">B8</option>
        <option value="B5">B5</option>
      </select>
    </td>
  </tr>
</table>
<input type="button" id="AddButton" value="Add">&nbsp;&nbsp;
<input type="button" id="SendButton" value="Send">

【讨论】:

  • 虽然链接可能会回答问题,但最好在此处发布答案的重要部分。
  • @cybermonkey 感谢您的建议。我会处理这些事情的。 :)
【解决方案3】:

我使用下面的代码解决了这个问题。我使用 angular ng-required 进行验证。 ng-required="property.model != null" 在两个输入字段中。

  <!-- VALUE -->
  <!-- Text field -->
 <div class="col-md-3" ng-if="property.dataTypeId === 3 ">
<input id="{{property.propertyId}}Value" name="QtePack" type="text"       class="form-control" ng-model="property.propertyValues[0].label" ng-required="property.startDate != null">
 </div>

   <!-- Date -->
 <div class="col-md-offset-2 col-md-1" ng-if="property.dataTypeId === 4 ">
 <datepicker date-format="dd/MM"> <input id="{{property.propertyId}}yearEnd" name="PackType" type="text" class="form-control" ng-model="property.propertyValues[0].label" ng-required="property.startDate != null"> </datepicker>
  </div>

 <!-- START DATE -->
                    <div class="col-md-2">
                        <datepicker date-format="yyyy-MM-dd"> <input
                            id="{{property.propertyId}}startDate" type="text" class="form-control"
                            ng-model="property.startDate" ng-required="property.propertyValues[0].label != null"> </datepicker>
                        <!-- <p class="input-group-addon glyphicon glyphicon-calendar"></p>   -->
                    </div>

  <div ng-if="formName == 'CREATE' ">
  <input type="submit" value="Add" ng-click="add()" ng-disabled="entityAddForm.$invalid" class="btn btn-primary">
   <button type="reset" class="btn btn-primary">Reset</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2010-11-04
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多