首页 > 解决方案 > PHP If 语句 html 选项值 0

问题描述

所以我在我的网站上有一个按钮,可以让人们将游戏类别添加到配置文件中,除非在下拉列表中选择了某些内容,否则我不知道用户能够单击添加到配置文件的内容。我已经尝试了一些东西,但我看到了我想要的结果,这是代码的表单块:

<div class="form-group">
        <label for="" class="col-md-3 control-label">Game Categories *</label>
        <div class="col-md-9">
            <select name="game_categories_id" id="game_categories_id" class="form-control">
                <option value="0">Select One...</option>
                <?php foreach ($game_categories as $game_category): ?>
                    <option value="<?php echo $game_category->ID; ?>">
                        <?php echo $game_category->name; ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

在我的提交区域中,我有以下内容:

<div class="modal-footer">
   <?php if (!empty($_POST['game_categories_id']) && ($_POST['game_categories_id'] == 0))  { ?>
       <button type="button" class="btn btn-primary" id="save_game_categories_id" ?>">Add Game</button>
   <?php } elseif (!empty($_POST['credit_reporting_org_id']) && ($_POST['credit_reporting_org_id'] != 0)) { ?>
       <button type="button" class="btn btn-primary" disabled id="save_game_categories_id" ?>">Add Game</button>
<?php } ?>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

我想要发生的是,在他们在下拉菜单中选择某些内容之前,“添加游戏”按钮是不可点击的,但现在除了关闭按钮之外什么都没有显示。

我也在一个处理添加游戏类别的 js 文件中有这个:

// Save game categories
$('#modal').on('click', '#save_game_categories_id', function() {
    var errors = 0;
    var $form = $('#add_game_categories_form');

    // Make sure game fields are filled
    $.each([$('#game_categories_id'), $('#game_type_id')], function(i, $input) {
        if ($input.val() == '' || $input.val() == 0) {
            $input.parents('.form-group').addClass('has-error');
            errors++;
        } else {
            $input.parents('.form-group').removeClass('has-error');
        }
    });

    if (errors > 0) return false; // Don't proceed if there are errors

    $.post('/game/approved_game/' + game_topic_id, $form.serialize(), function(
        data
    ) {
        if (data.success == true) {
            refresh_approved_game();
            $('#modal').modal('hide');
        } else {
            $form.find('.alert').show();
        }
    });
});

所以我已经有了js,我知道它可以添加游戏,但我只想能够禁用提交按钮,如果他们在下拉列表中选择任何东西

标签: javascriptphpdrop-down-menuselect-options

解决方案


您可能希望使用一些 Javascript 来完成此操作。您可以像这样使用 Jquery:

$('#game_categories_id').on('change', function(){
  var noAnswer = ($(this).val() == 0);
  $('#save_game_categories_id').attr('disabled', noAnswer);
});

如果您需要使用 Vanilla JS,我也可以在其中添加解决方案。


推荐阅读