如何将下拉列表文本与静态字符串进行比较

时间:2012-11-28 19:46:26

标签: jquery text drop-down-menu compare

好的,更清晰的画面(我希望)......

在HTML中,我有一个组合框(下拉列表)(id= "program"),即:您单击并选择一个值。组合框(下拉列表)上的提示文字是“选择一个程序......”

在此页面下方,我会显示一个按钮(id="addChosen")。在用户做出选择后,他们点击addChosen按钮将组合框中的文本添加到<textarea>,同时我将值$('#program :selected').val()添加到数组中:programArray.push($('program :selected').val());

因此,为了帮助用户从组合框中选择有效选项,我想停止添加“选择一个程序......”

我想将下拉列表中的文本与静态字符串进行比较:

if ($('#program :selected').text() == "Select a program..."); {
    //do something here, like show an alert for now...
    alert("Come on, you cant select the instructions...");
} 
else {
    //add the selected text to a <textarea>
    $('#chosenPrograms').append($('#program :selected').text() + "\n";
    }

这似乎没有比较所选文字,只需将“选择一个程序......”插入<textarea>

需要阻止用户向<textarea>

添加“选择程序...”

这是完整的页面:

@{
ViewBag.Title = "Subject Selector";
ViewBag.Header1 = "Subject Selector";
ViewBag.Header2 = "Choose the right subject - Grade 10-12.";
ViewBag.Description = "Have an idea of what and where you want to study? Subject Chooser will identify the subjects and requirements you will need to achieve your goal.";
}

<hgroup class="title">
    <h2>Select an institution, faculty and programme</h2>
</hgroup>



@using (Html.BeginForm("IndexDDL", "Home", FormMethod.Post, new { id="QueryProgrammesFormId", data_institutionListAction=@Url.Action("InstitutionList") } ))     {
<fieldset>
    <legend>Institution/Faculty/Programme/Chosen Programmes</legend>
    <label for="institution">Institution</label>
    @Html.DropDownList("institution", ViewBag.Institutions as SelectList, "Select an institution...", new { id = "institution", name = "institutionID" })
    <label for="faculty">Faculty</label>
    <select id="faculty" name="faculty"></select>  
    <label for="programme">Programme</label>
    <select id="programme" name="programme"></select>   
    <p>You can add up to <strong>5</strong> programmes to the list below:</p>
    <p>
        <input type="button" id="addChosen" name="addChosen" value="Add Programme" />&nbsp;
        <input type="button" id="removeChosen" name="removeChosen" value="Remove Programme" class="hidden" />
    </p>
    <label for="chosenProgrammes">Chosen Programmes</label> 
    <textarea id="chosenProgrammes" name="chosenProgrammes" rows="5" cols="" placeholder="Programmes selected for analysis"></textarea>
    <p>
        <input type="button" name="goButton" id="goButton" value="Analyse my Programmes" style="display:none" />
    </p>

</fieldset>

/*Tommy: Local Disclaimer to show only when the button becomes available*/
<div id="localDisclaimer" class="hidden">
    @Html.Partial("_LocalDisclaimer")
    <p>
        <input type="checkbox" name="AcceptDisclaimer" id="AcceptDisclaimer" /> I have read the Disclaimer and wish to continue.
    </p>
</div>
}

@section Scripts {
@Scripts.Render("~/bundles/cascadingdropdown")
<script type="text/javascript">
    var cnt = 1;
    var selectedProgrammes = [];
    $(function () {
        $("#faculty").CascadingDropDown("#institution", 'Query/GetFaculties',
        {
            promptText: 'Select a faculty...',
            onLoading: function () {
                $(this).css("background-color", "#ff3");
        },

        onLoaded: function () {
            $(this).animate({ backgroundColor: '#ffffff' }, 800, 'linear');
        }
    });
    $("#programme").CascadingDropDown("#faculty", 'Query/GetProgrammes',
    {
        promptText: 'Select a programme...',
        onLoading: function () {
            $(this).css("background-color", "#ff3");
        },

        onLoaded: function () {
            $(this).animate({ backgroundColor: '#ffffff' }, 800, 'linear');
        }
    });
    $('#programme').on('change', function () {
        if ($(this).val() == '') {
            $('#goButton').hide();
        }
        else {
        }
    });
    $('#AcceptDisclaimer').click(function () {
        if ($(this).attr('checked', 'checked')) {
            $('#goButton').show();
        }
    });
    $('#goButton').on('click', function () {
        /* 
        replace the call to Query/Results + programmeID 
        with
        SubjectSelector/Results + SelectedProgrammes[]
        */

        //window.location.href = 'Query/Results/' + $('#programme').val();
    });

    /*
    Before allowing the user to click on 'addChosen'
    check to see that the counter is less or equal to 5
    */

    $('#addChosen').click(function () {

        if ($('#programme:selected').val() == "Select a programme...") {
            alert("please make a proper selection");
        }
        else {
            $('#chosenProgrammes').append(cnt + " " + $('#programme :selected').text() + "\n");
            selectedProgrammes.push($('#programme :selected').val());
        };

        if (cnt <= 4) {
            //                $('#removeChosen').show();
            $('#localDisclaimer').show();
        }
        else {
            $('#addChosen').hide();
        };

        cnt += 1;
    });
});

    }

这是填充“程序”下拉列表的功能:

public ActionResult GetProgrammes(string faculty)
{
    int facultyInt = int.Parse(faculty);
        var programmes = db.Programmes.Where(p => p.Faculty.FacultyId == facultyInt)
                                      .OrderBy(p => p.Name)
                                      .Select(p => new SelectListItem()
                                      {
                                          Text = p.Name,
                                          Value = SqlFunctions.StringConvert((double)p.ProgrammeId)
                                      });
        return Json(programmes);
    }

3 个答案:

答案 0 :(得分:1)

试试这个:

if ($('#program').val() == 'Select a program...') {
    alert("Come on, you can't select the instructions...");
}

答案 1 :(得分:0)

在诊断这些问题时,最好先检查一下你的假设:

  • $('#program' :checked).text()返回什么?
  • 这就是你想要的吗?
  • :checked正确的选择器,你想要什么? (:selected也存在)
  • 如果不是,你怎么得到你想要的东西?

如果#program是您的select而不是option(因为#应该是唯一ID,这是有意义的),那么您甚至不需要伪选择器(:选择等)(对那个地方的巴马尔赞不绝口)

你的jQuery选择器中有一个错误的'我已经改变了(我不认为伪选择器前的空格也有效),加上下面的替代

if ($('#program:checked').text() == "Select a program..."; {
    alert("Come on, you cant select the instructions...");
} else {

    $('#chosenPrograms').append($('#program:checked').text() + "\n";
}

如果您的选项使用value属性(因为它允许您将可见值与值分开),请尝试:

if ($('#program:selected').val() == ""; {
    alert("Come on, you cant select the instructions...");
} else {
    $('#chosenPrograms').append($('#program:selected').val() + "\n";
}

答案 2 :(得分:0)

感谢所有添加回复的人,并试图帮助我。

我刚刚解决了问题:

我打电话给以下人员:
    if ('#programme:selected').val() =="")
我把它替换为:
    if ('#programme').val() = '')
(没有:selected speudo类)现在它可以工作!!

再次感谢Stackoverflow上的所有撰稿人!你们(和女孩们)真是太棒了!!