jQuery更改下拉列表值并禁用

时间:2015-03-20 05:42:22

标签: javascript php jquery html drop-down-menu

下拉一:

<select id="parent_task" name="parent_task" class="form-control input-large">
    <option data-task-hours="100" data-parent="0" data-task-category="2444" value="527"> - Requirement Analysis</option>
    <option data-task-hours="100" data-parent="0" data-task-category="2391" value="531"> - Development </option>
    <option data-task-hours="0" data-parent="0" data-task-category="2395" value="535"> - Miscellaneous </option>
</select>

下拉列表2:

PHP Code

<select name="task_category" id="task_category">
   <option value="">Please select</option>
   <?php foreach ($task_cat_arr as $cat_row) { ?>
   <option value="<?php echo $cat_row['CODEID'] ?>"><?php echo $cat_row['DESCRIPTION'] ?></option>
   <?php } ?>
</select>

Outputs:

<select id="task_category" name="task_category">
   <option value="">Please select</option>
   <option value="2444">Bug Fixing & Sustenance</option>
   <option value="2391">Configuration Management</option>
   <option value="2395">Database</option>
</select>

当用户从Requiremnet Analysis下拉菜单中选择parent_task时,如何从Bug Fixing & Sustenance下拉列表中选择task_category选项并将其设为selecteddisabled

它与data-task-category=2444关联,与task_category下拉列表的ID相同。

如何使用jQuery实现这一目标?

3 个答案:

答案 0 :(得分:0)

您可以使用

jQuery(function ($) {
    //change event handler for the parent
    $('#parent_task').change(function () {
        //$(this).find('option:selected')  - finds the selected option element
        //then its data attribute is read and that is set as teh value of the task category
        $('#task_category').val($(this).find('option:selected').data('taskCategory')).prop('disabled', true)
    })
})

演示:Fiddle

答案 1 :(得分:0)

试试这个:

$('#parent_task').on('change',function(){
    if($('#parent_task option:selected').val()=="527")
    {
        $('#task_category').val("2444");
        $('#task_category').attr('disabled',true);
    }
});

答案 2 :(得分:0)

jQuery(document).ready(function($){
    $('#parent_task').on('change', function(event) {
        if ($(this).val() === "527") {
            var taskCategory = $(this).find(':selected').data('task-category');
            $("#task_category").val(taskCategory).prop('disabled', 'disabled');
        } else {
            $("#task_category").prop('disabled', false);
        }
    });
});

http://jsfiddle.net/troythompson/rbbenefr/