Disable button if no selected value in dropdown

夙愿已清 提交于 2019-12-08 02:27:18

问题


I have a code where it disables the button on page load since the value of the dropdown is empty. However, when a value is selected (the values are from the database, it is populated and it is working), the button is still disabled.

Jquery:

<script>
    $(document).ready(function(){
        $('.send').attr('disabled',true);

        $('#kagawad').keyup(function(){
            if($(this).val() != ""){
                $('.send').attr('disabled', false);
            }
            else
            {
                $('.send').attr('disabled', true);        
            }
        })
    });
</script>

html:

<div class="item form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Select Kagawad</label>
    <div class="col-md-9 col-sm-9 col-xs-12">
    <?php
        include 'config.php';
        $selectSql = "SELECT firstName, middleName, lastName
                    FROM table_position p
                    LEFT JOIN person r ON p.Person_idPerson = r.idPerson
                    WHERE p.bar_position =  'Barangay Kagawad' AND p.activeOrInactive =  'Active'";
                    $result = mysqli_query($conn, $selectSql);
    ?>

        <select class="form-control" id = "kagawad" name = "kagawad" required>
            <option value="">Choose...</option>
            <?php
                while ($line = mysqli_fetch_array($result)) {
            ?>
            <option value="<?php echo $line['firstName'].' '.$line['middleName'].' '.$line['lastName'];?>"> <?php echo $line['firstName'].' '.$line['middleName'].' '.$line['lastName'];?> </option>

            <?php
                mysqli_close($conn);
                }
            ?>
        </select>
  </div> 
<button id="send" type="submit" class="send btn btn-success" name="addCedula">Save Record</button>

How can I do it? What do I need to modify my code? Thank you!


回答1:


  1. Use change event on the <select>.
  2. Instead of attr(), use prop() to set the disabled status.
  3. Use ID selector, to disable the button.

Code:

$('#kagawad').on('change', function () {
    $('#send').prop('disabled', !$(this).val());
}).trigger('change');


来源:https://stackoverflow.com/questions/35102464/disable-button-if-no-selected-value-in-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!