JQuery的新功能和我有以下功能。我試圖修改它,所以它做了2件事:當我點擊其他單選按鈕時,不會觸發該功能(我認爲'#UpdateType input [type =「radio」]'會這樣做),並且也會在加載時運行該函數如點擊。 #UpdateType是我正在使用它的單選按鈕的ID。有沒有人有什麼建議?JQuery函數 - 在點擊和頁面加載時運行特定的單選按鈕
$(document).ready(updateTypeFunc);
$(document).ready(function() {
$('#UpdateTypeRB input[type="radio"]').click(updateTypeFunc);
});
function updateTypeFunc()
{
if ($(this).attr('id') == 'UpdateType' && $(this).val() == 'Current') {
$('.current-employee').show();
}
else {
$('.current-employee').hide();
}
}
截至目前,當我點擊任何單選按鈕(無論ID如何)時都會觸發。
編輯:HTML
<div class="col-md-10" id="UpdateTypeRB">
<label class="radio-inline">
<input class="btn btn-primary" data-val="true" data-val-required="Please select whether the employee is new or current." id="UpdateType" name="UpdateType" type="radio" value="New"> New
</label>
<br>
<label class="radio-inline">
<input checked="checked" class="btn btn-secondary" id="UpdateType" name="UpdateType" type="radio" value="Current"> Current
</label>
<br>
<span class="field-validation-valid text-danger" data-valmsg-for="UpdateType" data-valmsg-replace="true"></span>
</div>
剃刀:
<div class="form-group">
@Html.LabelFor(m => m.UpdateType, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
<label class="radio-inline">
@Html.RadioButtonFor(m => m.UpdateType, "New", new { @class = "btn btn-primary" }) New
</label>
<br />
<label class="radio-inline">
@Html.RadioButtonFor(m => m.UpdateType, "Current", new { @class = "btn btn-secondary" }) Current
</label>
<br />
@Html.ValidationMessageFor(m => m.UpdateType, "", new { @class = "text-danger" })
</div>
</div>
編輯2:更新JQuery的感謝@KristianBarrett。除了我試圖實現的$(document).ready以外的其他作品。
我總體努力實現的是隱藏/顯示基於此單選按鈕打勾的頁面上的某些必需元素。它最初加載沒有檢查,所以用戶被迫選擇一個。然後,我使用Foolproof來根據這些複選框('Current'tick)執行RequiredIf,並且想要在用JQuery勾選'Current'之後向用戶顯示它們。問題是驗證在提交後拋出一個ErrorMessage時,當前複選框被打勾,但是這些字段被隱藏,直到我再次手動點擊它。這些字段默認爲隱藏。
你的HTML看起來像什麼? '$('#UpdateType input [type =「radio」]')'表示運行這個處理器,處理ID爲「UpdateType」的容器中的任何無線電。 – tymeJV
被編輯。那麼這是否意味着我的Razor語法會因爲#UpdateType的兩個ID而搞砸了? – justiceorjustus
好吧 - 你不能有兩個相同的ID - ** ID必須是唯一的** – tymeJV