如何动态创建dropdownlist的ID,并检查其值是否改变

How to get dynamically created DropDownList's ID and check if its value changed or not?

本文关键字:检查 改变 是否 ID 何动态 动态 dropdownlist 创建      更新时间:2023-09-26

在Steven Sanderson的博客的帮助下,我实现了一个视图,其中动态数量的文本框和下拉列表生成。一切正常。但我想,直到每个下拉列表有一个值,表单不能提交,也如果没有下拉列表我的意思是所有的动态内容被删除,那么表单必须不提交。

主视图代码:

<div id="Part2">
 <h3><u>Services:</u></h3><br />
 <div id="EditorRows">
  <%Html.RenderPartial("_InsertServices", Model);%>
 </div>
 <div id="DontAppend">
  <%= Html.ActionLink("+ Add Another Service", "Add", null, new { id = "addItem" }) %>
  <input type="button" id="btnEdit" value="Edit" hidden="hidden"/>
  <input type="button" id="btnDone" value="Done" />
 </div>
</div>

PartialVew代码:

<div class="EditorRow">
 <% using (Html.BeginCollectionItem("services")){ %>
 <table id="table1">
  <tr>
   <td>NOS:</td>
   <td><%:Html.DropDownListFor(model=>model.Id,(SelectList)ViewData["crmServiceType"] as SelectList,"---")%></td>
   <td>Comment:</td>
   <td><%=Html.TextBoxFor(model => model.Comment, new { size = "20" })%></td>
   <td><a href="#" class="deleteRow">delete</a></td>
  </tr>
 </table>
<% } %>
</div>
JavaScript:

$("#addItem").click(function () {
  $.ajax({
  url: this.href,
  cache: false,
  success: function (html) { $("#EditorRows").append(html); }
  });
  return false;
});
$("a.deleteRow").live("click", function () {
  $(this).parents("div.EditorRow:first").remove();
  return false;
});

如果我理解正确的话,你的标记看起来像

<div class="EditorRow">
    <input type="hidden" value="6c2fa95a-cc3e-44d9-b460-b561276196c1" autocomplete="off" name="services.index">
    <table id="table1">
    <select>
        <option value="">Select</option>
        <option value="1">Value1</option>
        <option value="2">Value2</option>
    </select>
</div>

你可以这样做

$(function(){
    $("#btnDone").click(function(){
        if ($("div.EditorRow").length) {
            $("div.EditorRow select").each(function(){
                if (!$(this).val()) {
                    alert("You need to choose a value before submit");
                    return false;
                }
                //do your submit
            });
        } else {
            alert("You need to add at least one service before submit.")
        }
    });
});

.live()已弃用,now removed in jQuery version 1.9+因此使用.on()处理器代替。
不知道为什么你添加了:first,我猜你有多个EditorRowdiv,如果是这样的话,那么你应该试试这个:

 $("#EditorRows").on("click", "a.deleteRow", function () {
    var selID = $(this).closest("div.EditorRow").find('select').attr('id'); //<--give you the select list id
    $(this).closest("div.EditorRow").andSelf().remove();
    return false;
 });

不知道你想要在哪里,但是你可以这样做:

$("#EditorRows").find('select').attr('id');