JQuery:append/remove 必填字段需要星号

JQuery: append/remove required asterisk to required field

正在尝试编写 JQuery 函数以将必填星号附加到按条件触发的必填字段。我认为这个 .append 语句会起作用,但它不起作用。

Jquery:

       function checkRequiredField(){
                var someId = $('#Id').val();
                if (someId == 106587){          //value to trigger
                    $('#someNumberField').prop('required',true);
     THIS LINE -->  $('#someNumberField-label').append('<span class="required-indicator">*</span>');
                }else{
                    $('#someNumberField').removeAttr('required');
                    $('#someNumberField-label').remove('<span class="required-indicator">*</span>');
}

HTML:

<div class="form-group">
    <label id="SomeId-label" class="col-sm-2 control-label" for="SomeId">SomeId<span class="required-indicator">*</span></label>
    <div class="col-sm-5">
        <g:select name="SomeId" noSelection="['null':'']" from=".." value="${106587}" class="form-control" optionKey="id" required="" aria-labelledby="SomeId-label" onchange="checkRequiredField()"/>
    </div>
</div>


<div class="form-group">
    <div class="col-sm-2">
        <label id="someNumberField-label" class="toplabel" for="someNumberField">Number #</label>
        <g:textField name="someNumberField" id="someNumberField" value="${aphis104Instance.someNumberField}" class="form-control" aria-labelledby="someNumberField-label"/>
    </div>
</div>
    }

这里是工作 fiddle : http://jsfiddle.net/kLaaq0dc/2/

function checkRequiredField(){
            var someId = $('#Id').val();

            if (someId == 106587){         
                $('#someNumberField').prop('required',true);
   $('#someNumberField-label').append('<span class="required-indicator">*</span>');
            }else{
                $('#someNumberField').removeAttr('required');
                $('#someNumberField-label span').remove();
    }

}

这样试一下,应该可以的。

function checkRequiredField() {
    var someId = $('#Id').val();
    if (someId == 106587) {
        $('#someNumberField').prop('required',true);
        // make sure its getting here... alert("test")
        $('#someNumberField-label').append(
            $("<span>", {"class": "required-indicator"}).text("*")
        );
    } else {
        $('#someNumberField').removeAttr('required');
        $('#someNumberField-label span').remove();
    }
}