替换选择字段中的选项(不添加)

时间:2015-08-21 05:53:53

标签: javascript html regex

我有一个选择字段如下:

<div data-bind="foreach: GuidelinesQuestionList" id="problemcollapse">
                <div data-bind="foreach: $data.SectionsSet">
                    <div class="primaryCaseContainer">
                        <div class="questionHeader" data-bind="text: $data.Heading , attr:{onClick: 'variableName.CollapseExpandCustom.ToggleSection(\''+$data.Uid.replace(/[^\w\s]/gi, '')+'\')'}"></div>
                        <div data-bind="attr: {id: $data.Uid.replace(/[^\w\s]/gi, '')}">
                            @{int count = 0;}
                            <div class="questionContainer" data-bind="foreach: $data.ProblemsSet">

                                <div data-bind="if: $data.Identified">
                                    @{count++;}
                                    <div>
                                        <a href="" data-bind="text: $data.Text , click: $root.ProblemClick , attr:{id: $data.Id,Uid: $data.Uid , Rid: $data.Uid.replace(/[^\w\s]/gi, '')}"></a>
                                        <br><br>
                                        <div data-bind="attr: {id: 'goalsReplaceDiv'+$data.Uid.replace(/[^\w\s]/gi, '')}"></div>
                                    </div>
                                </div>


                            </div>
                            @if (count == 0)
                            {
                                <div id="divNoRecordsMessage">
                                    <div>No Records !! </div>
                                </div>
                            }
                        </div>
                    </div>
                </div>
            </div>

我根据在我的页面上的另一个div(OtherDiv)中找到的值添加选项,如下所示:

<select id="field">

但是,如果正则表达式没有匹配项,我想为该字段设置一些替代值。我怎样才能做到最好?

1 个答案:

答案 0 :(得分:1)

使用条件

window.onload = function onload()
{
    var OtherDiv = document.getElementById('OtherDiv').innerHTML;
    var result = OtherDiv.match(/SomeRegex/gi);
    var select = document.getElementById("field");
    if(result.length){
        for(var i = 0; i < result.length; i++)
            {
                var option = document.createElement("option");
                option.value = i+1;
                option.innerHTML = result[i];
               select.add(option);
            }
      }else{
           //add alternative options here
           var option = document.createElement("option");
                option.innerHTML = "No records found"; //whatever text you want to show 
               select.add(option);
      }
}