Having issue with Javascript

Having issue with Javascript

本文关键字:Javascript with issue Having      更新时间:2023-09-26

这是我的代码:JS PART

$(document).ready(function(){
    $("#parent").hide();
    $(".parentcheck").click(function(){
            if($(this).val()==="1") 
            {
                $("#parent").show();
                $('#switch').attr('disabled', '');
            }
            else {
                $("#parent").hide();
                $('#switch').attr('disabled', 'disabled');
            }
    });
    $("#switch").change(function () {
    var selectedSwitch = $("#switch").val();
    var parentcheck = $(".parentcheck:checked").val();
    if (selectedSwitch!='' && selectedSwitch!='0'){
    $.ajax({
    type: "POST",
    url : "optionsgenerator.php",
    data: {menu: selectedSwitch},
    success: function(result, status, xResponse){
        if (result!=''){
            if($('#parentcheck').attr('checked')){
                $("#parent").hide();
            }
            else {
                $("#parent").html(result);
                $("#parent").show();
            }
        }
        else{
            alert('Error occured.');
            $("#parent").hide();
        }
    },
    error: function(e){
        alert(e);
    }
    });
    }
    else
    $("#parent").hide();
});
});

和HTML标记

<select name="switch" id="switch">
<option value="" selected="selected">Select one...</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="0">no one</option>
</select>
<div class="parent">
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
</div>

问题是

如果单选按钮与类"parentcheck"的值是1,我的js显示选择框没有检查它是否有东西要显示(在我的情况下从后端php代码返回的选项)或不

我正在努力实现以下

如果"parentcheck"类单选按钮的值1则为show选择#parent 仅当ajax已经返回的东西启用选择#switch

您试图通过id获取parentcheck,但parentcheck是一个类:

var parentcheck = $("#parentcheck:checked").val();

尝试更改为

var parentcheck = $(".parentcheck:checked").val();

编辑:取消选择:

       if($(this).val()==="1") 
        {
            if ($("#parent option").length > 0) {
                 $("#parent").show();
            }
            $('#switch').attr('disabled', '');
        }
        else {
            $("#parent").hide().find('option:selected').removeAttr('selected');
            $('#switch').attr('disabled', 'disabled').find('option:selected').removeAttr('selected');
        }

解决方案:

1)

 if(selectedSwitch != '' && selectedSwitch !=0)

  • 您正在缩短OR语句,需要使用AND。

2)

$(".parentcheck").click(function(){
        if($(this).val() == "1") 
        {
            $('#parent).show();
            $('#switch').attr('disabled', '');
        }
        else {
            $('#parent').val('');
            $('#parent').hide();
            $('#switch').val("Select one...");
            $('#switch').attr('disabled', 'disabled');
        }
});

  • 要设置select的值,你需要给它你想要的索引的实际值。

3)在AJAX函数中设置一个布尔标志,然后在单击侦听器中只启用selectbox if(标志)。