javascript - Make radio button not checked on load of form? -


i have slight problem here each time run application first radio button checked, want make nun of radio buttons checked. how do this?

 <div class="col-md-12">      <!--<i class="fa fa-child" aria-hidden="true"></i>-->      @html.labelfor(model => model.ccommmunication, "choose preferred way of communication", new { @style = "", @class = "", id = "" })      <span style="color: red;">*</span>      @*@html.dropdownlistfor(model => model.profession, new selectlist(model.professions, "id", "name"), new { placeholder = "", @style = "", @class = "form-control", id = "profession" })*@      @html.enumradiobuttonfor(model => model.ccommmunication, false,false,"communicationcb") <!--first 2 paramerters false false communicationcb class-->      @html.validationmessagefor(model => model.ccommmunication)  </div> 

this model

[required(errormessage = "please select preferred way of communication option")]         public commmunication ccommmunication         { get; set; }          public enum commmunication         {             [display(name = "email", order = 0)]             email,              [display(name = "mobile telephone", order = 1)]             telephoneno,              [display(name = "alternative telephone", order = 2)]             telephonenoalternative         } 

this javascript

<script>          var checkedval = $('.communicationcb input[name=ccommmunication]:checked').val(); //added variable check value         if (checkedval == "telephoneno") { //if checked valuie             $('.confirmmobtelno').show(); //show text box         } else {             $('.confirmmobtelno').hide(); //hide textbox         };          if (checkedval == "telephonenoalternative") {  //if checked valuie == telephonenoalternative             $('.confirmalttelno').show(); //show confirm alt tel no text box         } else {             $('.confirmalttelno').hide(); //else hide         };            $('.communicationcb input[name=ccommmunication]').click(function () { //.communication class passed input name == model public communication             if ($(this).val() == "telephoneno") { //if value telephoneno selected in model                 $('.confirmmobtelno').show(); //show text box             } else {                 $('.confirmmobtelno').hide(); //hide textbox             }              if ($(this).val() == "telephonenoalternative") {  //if value == telephonenoalternative                 $('.confirmalttelno').show(); //show confirm alt tel no text box             } else {                 $('.confirmalttelno').hide(); //else hide             }         }); 

finally have enumradiobutton.cs

  public static class htmlhelper     {         public static mvchtmlstring enumradiobuttonfor<tmodel, tproperty>(                 htmlhelper<tmodel> htmlhelper,                 expression<func<tmodel, tproperty>> expression,                 bool includenoneoption = true,                 bool isdisabled = false,                 string cssclass = null             ) tmodel : class         {             var memberexpression = expression.body memberexpression;             if (memberexpression == null)                 throw new invalidoperationexception("expression must member expression");              var name = expressionhelper.getexpressiontext(expression);             var fullname = htmlhelper.viewcontext.viewdata.templateinfo.getfullhtmlfieldname(name);             modelstate currentvalueinmodelstate;             var couldgetvaluefrommodelstate = htmlhelper.viewdata.modelstate.trygetvalue(fullname, out currentvalueinmodelstate);             object selectedvalue = null;             if (couldgetvaluefrommodelstate && htmlhelper.viewdata.model != null)             {                 selectedvalue = expression.compile()(htmlhelper.viewdata.model);             }              var enumnames = getselectitemsforenum(typeof(tproperty), selectedvalue).where(n => !string.isnullorempty(n.value)).tolist();               var metadata = modelmetadata.fromlambdaexpression(expression, htmlhelper.viewdata);             var sb = new stringbuilder();             sb.appendformat(                 "<ul class=\"radio-button-list{0}\">",                 string.isnullorempty(cssclass) ? string.empty : " " + cssclass);             foreach (var enumname in enumnames)             {                 var id = string.format(                     "{0}_{1}_{2}",                     htmlhelper.viewdata.templateinfo.htmlfieldprefix,                     metadata.propertyname,                     enumname.value                     );                  if (id.startswith("-"))                     id = id.remove(0, 1);                  var value = enumname.value;                  sb.appendformat(                       //"<li>{2} <label for=\"{0}\">{1}</label></li>", //originol puts data in list                        "{2} <label for=\"{0}\">{1}</label>",                     id,                     httputility.htmlencode(enumname.text),                     isdisabled                         ? htmlhelper.radiobuttonfor(expression, value, new { id, disabled = "disabled" }).tohtmlstring()                         : htmlhelper.radiobuttonfor(expression, value, new { id }).tohtmlstring()                     );             }             sb.append("</ul>");             return mvchtmlstring.create(sb.tostring());         }         public static ilist<selectlistitem> getselectitemsforenum(type enumtype, object selectedvalue)         {             var selectitems = new list<selectlistitem>();              if (enumtype.isgenerictype &&                 enumtype.getgenerictypedefinition() == typeof(nullable<>))             {                 enumtype = enumtype.getgenericarguments()[0];                 selectitems.add(new selectlistitem { value = string.empty, text = string.empty });             }              var selectedvaluename = selectedvalue != null ? selectedvalue.tostring() : null;             var enumentrynames = enum.getnames(enumtype);             var entries = enumentrynames                 .select(n => new                 {                     name = n,                     displayattribute = enumtype                         .getfield(n)                         .getcustomattributes(typeof(displayattribute), false)                         .oftype<displayattribute>()                         .singleordefault() ?? new displayattribute()                 })                 .select(e => new                 {                     value = e.name,                     displayname = e.displayattribute.name ?? e.name,                     order = e.displayattribute.getorder() ?? 50                 })                 .orderby(e => e.order)                 .thenby(e => e.displayname)                 .select(e => new selectlistitem                 {                     value = e.value,                     text = e.displayname,                     selected = e.value == selectedvaluename                 });              selectitems.addrange(entries);              return selectitems;         }      }  } 

to have none of radio buttons selected, make property nullable

[required(errormessage = "please select preferred way of communication option")] public commmunication? ccommmunication { get; set; } 

if ccommmunication has initial value of null, no radio buttons selected.

but unclear trying (unnecessary) code in extension method, in particular why creating ilist<selectlistitem> (which generating <select> tag). helper can be

 public static class radiobuttonhelper  {     public static mvchtmlstring enumradiobuttonlistfor<tmodel, tvalue>(this htmlhelper<tmodel> helper, expression<func<tmodel, tvalue>> expression)     {         modelmetadata metadata = modelmetadata.fromlambdaexpression(expression, helper.viewdata);         string name = expressionhelper.getexpressiontext(expression);         type type = nullable.getunderlyingtype(metadata.modeltype);         if (type == null || !type.isenum)         {             throw new argumentexception(string.format("the property {0} not enum", name));         }         stringbuilder html = new stringbuilder();         foreach (enum item in enum.getvalues(type))         {             string id = string.format("{0}_{1}", metadata.propertyname, item);             stringbuilder innerhtml = new stringbuilder();             innerhtml.append(helper.radiobuttonfor(expression, item, new { id = id }));             innerhtml.append(helper.label(id, item.todescription()));             tagbuilder div = new tagbuilder("div");             div.addcssclass("radiobutton");             div.innerhtml = innerhtml.tostring();             html.append(div.tostring());         }         tagbuilder container = new tagbuilder("div");         container.addcssclass("radiobutton-container");         container.innerhtml = html.tostring();         return mvchtmlstring.create(container.tostring());     } } 

which uses following extension method

public static class enumextensions {     public static string todescription(this enum value)     {         if (value == null)         {             return null;         }         fieldinfo field = value.gettype().getfield(value.tostring());         descriptionattribute[] attributes = (descriptionattribute[])field             .getcustomattributes(typeof(descriptionattribute), false);         if (attributes.length > 0)         {             return attributes[0].description;         }         return value.tostring();     } } 

in association [description] attribute applied enum values rather [display] attribute (but can modify that)


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -