簡體   English   中英

POST動態創建所需的輸入字段

[英]POST dynamically created required input fields

這是我用於POST數據的代碼,它可以正常工作,在我添加了必需的參數后出現了問題,現在代碼強制填充所有字段,即使它們不可見。 我猜問題出在jQuery的hide()函數中,因為它只隱藏字段。 應該進行哪些更改以使此代碼僅需要可見字段?

 $('#product_type').change(refresh_inputs); refresh_inputs(); function refresh_inputs() { var name = $('#product_type').attr('name'); var val = $('#product_type').val(); $('#'+name+' div').hide(); $('#'+val).show(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="add.php" method="post" name="form1" > <table width="25%" border="0"> <tr> <td>SKU</td> <td><input type="text" name="sku" required></td> </tr> <tr> <td>Name</td> <td><input type="text" name="name" required></td> </tr> <tr> <td>Price</td> <td><input type="text" name="price" required></td> </tr> <tr> <td>Select product type</td> <td> <select id="product_type" name="products" required> <option style="display: none;" selected>Select product type</option> <option value="book">Book</option> <option value="dvd">Dvd</option> <option value="furniture">Furniture</option> </select> </td> </tr> <tr> <td> <div id="products"> <div id="book"> <input type="text" name="weight" placeholder="Weight" required/> </div> <div id="dvd"> <input type="text" name="capacity" placeholder="Capacity" required/> </div> <div id="furniture"> <input type="text" name="height" placeholder="Height" required/> <input type="text" name="width" placeholder="Width" required/> <input type="text" name="length" placeholder="Length" required/> </div> </div> </td> </tr> <tr> <td></td> <td><input type="submit" name="Submit" value="Add"></td> </tr> </table> </form> 

<script type="text/javascript">
        $('#product_type').change(refresh_inputs);
        refresh_inputs();
        function refresh_inputs() {
            var name = $('#product_type').attr('name');
            var val = $('#product_type').val();
            $('#'+name+' div').attr("required", false); // add this line only
            $('#'+name+' div').hide();
            $('#'+val).show();
         }
</script>

它隱藏了元素,不會根據需要刪除您自己設置的屬性。

您可以按以下方式修改refresh_inputs函數:

<script type="text/javascript">
    $('#product_type').change(refresh_inputs);
    refresh_inputs();
    function refresh_inputs() {
        var name = $('#product_type').attr('name');
        var val = $('#product_type').val();
        $('#'+name+' div').hide();
        $('#'+name+' div').find('input').removeAttr('required');
        $('#'+val).show();
        $('#'+val).find('input').attr('required', 'required');
    }
</script>

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM