如何根据下拉选择提交显示的div

时间:2019-05-16 13:17:38

标签: javascript jquery razor

我有这两个div和一个下拉菜单。我能够根据下拉选择显示div。默认情况下,在页面显示中,我在下拉列表和div1中显示option1。我的问题是,当我选择option2并在div2中输入详细信息并提交页面时,我的下拉值保持正确,但是div返回div1并向用户显示div1的验证消息。如何使显示的div及其值按页面上的原样提交?

$('#purpose').on('change', function () {
    if (this.value == '1') {
        $("#div1").show();
         $("#div2").hide();
    } else {
        $("#div1").hide();
         $("#div2").show();
    }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
    @using (Html.BeginForm("Customer", "Home", FormMethod.Post))
    {

<select id='purpose'>
    <option value="1">Div1</option>
    <option value="2">Div2</option>
</select>
<div id='div1'>DIV 1 Details
       <input type='text' class='text' name='div1' />
    <br/>
</div>
<div id='div2' style='display:none;'>DIV 2 Details
       <input type='text' class='text' name='div2' />
    <br/>
</div>
  <button type="submit" class="btn btn-tertiary" id="buy">Buy </button>
  }
  </div>

1 个答案:

答案 0 :(得分:0)

检查模型以查看“目的”的值是什么,并根据其显示正确的div和选项

<div id="main">
  @using (Html.BeginForm("Customer", "Home", FormMethod.Post)) 
  {
    <select id='purpose'>
      <option value="1"@(Model.Purpose == 1 ? " selected" : string.Empty)>Div1</option>
      <option value="2"@(Model.Purpose == 2 ? " selected" : string.Empty)>Div2</option>
    </select>
    <div id='div1'@(Model.Purpose == 2 ? " style='display:none;'" : string.Empty)>DIV 1 Details
      <input type='text' class='text' name='div1' />
      <br/>
    </div>
    <div id='div2'@(Model.Purpose == 1 ? " style='display:none;'" : string.Empty)>DIV 2 Details
      <input type='text' class='text' name='div2' />
      <br/>
    </div>
    <button type="submit" class="btn btn-tertiary" id="buy">Buy </button> 
  }
</div>