Py学习  »  Jquery

jquery只显示所选选项之一+必需

James • 4 年前 • 725 次点击  

目前我有一个问题,我显示所有的选项,只有选定的选项是必要的。如果未选择任何选项,则仅当选择其中一个选项时,才不显示该选项。

所选选项应具有必需字段。因为两者都是必需的,所以无法提交。

谢谢你的解释、建议和支持。

$(document).ready(function(){

$('#problem').on('change', function(){
$('.display, .display_1').show();


if (this.value.trim()) {
   if (this.value !== 'test') {
   $('.display').hide();
   }

if (this.value !== 'test1') {
   $('.display_1').hide();
   }   
  }
 });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<form id="e">
<table id="tableId">
<tr>	
<td>Problem:</td>
<td><select required id="problem" name="problem">
<option value=""></option>
<option value="test">test</option>		
<option value="test1">test1 </option>
</select>
</td>
</tr>


<tr class="display">
<td>Router</td>
<td><input id="router" name="router" type="text" maxlength="50" size="50" required></td>
</tr>

<tr class="display_1">
<td>Switch</td>
<td><input id="switch" name="switch" type="text" maxlength="50" size="50"    required></td>
</tr>
<tr>
 <td><input type="submit"  class="submit" value="submit"></td>
</tr>
</table>
</form>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46719
 
725 次点击  
文章 [ 1 ]  |  最新文章 4 年前
symlink
Reply   •   1 楼
symlink    4 年前

我清理了html并添加了一些css。基本上这是一个简单的 if 根据select语句的值显示一个或另一个输入字段的语句:

$(document).ready(function(){

    $("#problem").on("change", function(){
        $(".input.text").hide();
        $(".input.text input").removeAttr("required");
        if(this.value === "test"){
            $(".input.text#router").show();
            $(".input.text#router input").prop("required", true);
        }else if(this.value === "test1"){
            $(".input.text#switch").show();
            $(".input.text#switch input").prop("required", true);
        }
    });
});
form .input{
   display: flex;
   margin-bottom: 10px;
}

form .input input, form .input select{
   margin-left: 20px;
}

form .input.text{
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<form id="e">
    <div class="input">
        <span>Problem:</span>
        <select required id="problem" name="problem">
            <option value=""></option>
            <option value="test">test</option>		
            <option value="test1">test1 </option>
         </select>
    </div>
    <div class="input text" id="router">
        <span>Router</span>
        <input id="router" name="router" type="text" maxlength="50" size="50">
    </div>
    <div class="input text" id="switch">
        <span>Switch</span>
        <input id="switch" name="switch" type="text" maxlength="50" size="50">
    </div>
    <input type="submit"  class="submit" value="submit">
</form>