JQUERY 設定 RadioButton 的值

  • 1155
  • 0
  • MVC
  • 2019-06-26

依照要判斷的值,使用JQUERY去設定RadioButton勾選

前端的HTML

<label class="radio-inline control-label"><input type="radio" value="A" name="condition.rdoAnnCategory">POPUP+跑馬燈</label>
<label class="radio-inline control-label"><input type="radio" value="P" name="condition.rdoAnnCategory">POPUP</label>
<label class="radio-inline control-label"><input type="radio" value="M" name="condition.rdoAnnCategory">跑馬燈</label>

有三個選項,value分別是A、P、M

現在想要使用jquery依照value去設定勾選,以下jquery為設定方法,vaue是要設定的值

//初始化公告方式 Radio Button
var _value = $('#hidAnnCatrgory').val();
var $radios = $('input:radio[name="condition.rdoAnnCategory"]');
if ($radios.is(':checked') === false) {
    $radios.filter('[value=' + _value + ']').prop('checked', true);
}

如果這語法要改為 在MVC架構底下使用RAZOR+BS產生,其實也很方便

在ViewModel.cs裡面設定一個 rdoAnnCategory

//View
public class Condition 
{
   //公告方式
   public String rdoAnnCategory { get; set; }
}

public class ViewModel
{
   public Condition condition{get;set;}
}

Controller 內直接指定資料

vieModel.condition.rdoAnnCategory = "A";

最後在View裡面寫法如下:

<div class="col-md-6">
  <div class="radio-inline">
	@Html.RadioButtonFor(c => c.condition.rdoAnnCategory, "A", new { id = Html.IdFor(c => c.condition.rdoAnnCategory) + "_ALL", style = "cursor:pointer;" })
	@Html.Label(Html.IdFor(c => c.condition.rdoAnnCategory) + "_ALL", "POPUP+跑馬燈", new { @class = "", style = "cursor:pointer;" })
  </div>
  <div class="radio-inline">
	@Html.RadioButtonFor(c => c.condition.rdoAnnCategory, "P", new { id = Html.IdFor(c => c.condition.rdoAnnCategory) + "_POPUP", style = "cursor:pointer;" })
	@Html.Label(Html.IdFor(c => c.condition.rdoAnnCategory) + "_POPUP", "POPUP", new { @class = " ", style = "cursor:pointer;" })
  </div>
  <div class="radio-inline">
	@Html.RadioButtonFor(c => c.condition.rdoAnnCategory, "M", new { id = Html.IdFor(c => c.condition.rdoAnnCategory) + "_MARQUEE", style = "cursor:pointer;" })
	@Html.Label(Html.IdFor(c => c.condition.rdoAnnCategory) + "_MARQUEE", "MARQUEE", new { @class = " ", style = "cursor:pointer;" })
  </div>
</div>

這樣就可以依照使用者選設定的值去勾選,

最後ModelBinding的時候也很方便,

直接判斷POST到後端 condition.rdoAnnCategory 的值就可以了。