【问题标题】:.prop('selected') not working, button is disabled all the time in jquery.prop('selected') 不起作用,按钮在 jquery 中一直被禁用
【发布时间】:2015-05-11 13:23:12
【问题描述】:

我想在选择字段中的状态被选中后启用提交按钮。

<div class="close_req">
    <div class="req_status">
        <select id="status_update">
            <option value="status" selected="selected" disabled="disabled">Status</option>
            <option value="complete">Complete</option>
            <option value="pending">Pending</option>
        </select>
    </div>
    <div class="req_addcharges">
        <select id="additional_charges">
            <option value="charge">Additional Charges</option>
            <option value="complete">Yes</option>
            <option value="pending">No</option>
        </select>
    </div>
    <div class="additional_charge">
        <input type="text" id="add_price" name="add_price" placeholder="Enter the additional charge" />
    </div>
    <div class="task_desc">
        <textarea id="task" name="task" cols="10" rows="6" placeholder="Description of the task"></textarea>
    </div>
    <div class="task_complete">
        <input type="submit" id="complete" name="complete" value="Task Complete" />
    </div>
    </form>
</div>

这是我尝试过的 jquery 脚本

$(document).ready(function () {
    $("#complete").attr("disabled", "disabled");

    function updateFormEnabled() {
        if ($("#status_update").prop('selected', true)) {
            $("#complete").removeAttr('disabled');
        } else {
            $("#complete").attr('disabled', 'disabled');
        }
    }
});
$("#status_update").change(updateFormEnabled);

但提交按钮始终处于禁用状态,我希望在选择字段中选择状态后启用该按钮。谁能帮我解决这个问题。

【问题讨论】:

  • 谢谢大家的建议,对我帮助很大。

标签: javascript jquery html css


【解决方案1】:

你的状态不好,应该是

if ($("#status_update").prop('selected') == true)

【讨论】:

  • 使用JS的也应该是===
【解决方案2】:

$("#status_update").change(updateFormEnabled); 应该在$(document).ready(function () {});

【讨论】:

  • 另一种选择是使用.live(),而不是准备好它
  • (但建议的解决方案更好)
【解决方案3】:

#status_update 是选择列表而不是选项,您必须改为检查所选选项:

function updateFormEnabled() {
        $("#complete").attr('disabled', 'disabled');
        $('#status_update option').each(function() {
           if($(this).is(':selected')){
               $("#complete").removeAttr('disabled');
               return;
           }
        }
    }
$("#status_update").change(updateFormEnabled);

【讨论】:

    【解决方案4】:

    另一种方法是

    if($("#status_update option:selected").length) {/* do action */}

    JSFiddle

    http://jsfiddle.net/9pqekb63/1/

    【讨论】:

    • 是的! JSFiddle 是一个很棒的工具:-D
    猜你喜欢
    • 1970-01-01
    • 2019-03-08
    • 2017-08-28
    • 1970-01-01
    • 2013-10-09
    • 2021-10-08
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多