如何使用javascript实现隐藏和显示单选按钮

How to implement hiding and showing radiobuttons using javascript

本文关键字:显示 单选按钮 隐藏 实现 何使用 javascript      更新时间:2023-09-26

我在一个网站上看到了这个例子,我正在学习如何为这种类型的视图实现javascript或JQuery。其中没有分配id。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Text;
namespace MVC3_RadioButtonList_Helper_Sample
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            IEnumerable<SelectListItem> listOfValues)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var sb = new StringBuilder();
            if (listOfValues != null)
            {
                // Create a radio button for each item in the list
                foreach (SelectListItem item in listOfValues)
                {
                    // Generate an id to be given to the radio button field
                    var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
                    // Create and populate a radio button using the existing html helpers
                    var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
                    var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
                    // Create the html string that will be returned to the client
                    // e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label>
                    sb.AppendFormat("<div class='"RadioButton'">{0}{1}</div>", radio, label);
                }
            }
            return MvcHtmlString.Create(sb.ToString());
        }
    }
}

型号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MVC3_RadioButtonList_Helper_Sample.Models
{
    public class IndexViewModel
    {
        public IEnumerable<SelectListItem> TestRadioList { get; set; }
        public IEnumerable<SelectListItem> TestRadioList2 { get; set; }
        [Required(ErrorMessage = "You must select an option for TestRadio")]
        public String TestRadio { get; set; }
        [Required(ErrorMessage = "You must select an option for TestRadio2")]
        public String TestRadio2 { get; set; }
    }
    public class aTest
    {
        public Int32 ID { get; set; }
        public String Name { get; set; }
    }
}

Contoller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3_RadioButtonList_Helper_Sample.Models;
namespace MVC3_RadioButtonList_Helper_Sample.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/
        public ActionResult Index()
        {
            List<aTest> list = new List<aTest>();
            list.Add(new aTest() { ID = 1, Name = "Line1" });
            list.Add(new aTest() { ID = 2, Name = "Line2" });
            list.Add(new aTest() { ID = 3, Name = "Line3" });
            SelectList sl = new SelectList(list, "ID", "Name");
            List<aTest> list2 = new List<aTest>();
            list2.Add(new aTest() { ID = 1, Name = "test1" });
            list2.Add(new aTest() { ID = 2, Name = "test2" });
            SelectList sl2 = new SelectList(list2, "ID", "Name");
            var model = new IndexViewModel();
            model.TestRadioList = sl;
            model.TestRadioList2 = sl2;
            model.TestRadio = "2";  // Set a default value for the first radio button helper
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(IndexViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                ModelState.AddModelError("", "Always force an error to be raised so we can test the postback sets the radio buttons to their last values.");
            }
            // If we got this far, something failed, redisplay form
            List<aTest> list = new List<aTest>();
            list.Add(new aTest() { ID = 1, Name = "Line1" });
            list.Add(new aTest() { ID = 2, Name = "Line2" });
            list.Add(new aTest() { ID = 3, Name = "Line3" });
            SelectList sl = new SelectList(list, "ID", "Name");
            List<aTest> list2 = new List<aTest>();
            list2.Add(new aTest() { ID = 1, Name = "test1" });
            list2.Add(new aTest() { ID = 2, Name = "test2" });
            SelectList sl2 = new SelectList(list2, "ID", "Name");
            model.TestRadioList = sl;
            model.TestRadioList2 = sl2;
            return View(model);
        }
    }
} 

查看

<div>
@Html.RadioButtonForSelectList(m => m.TestRadio, Model.TestRadioList)
@Html.ValidationMessageFor(m => m.TestRadio)
</div>
<div id= "testdiv1" style="display:none">
  Show this content when Line1 is selected
<div>
<div id="testdiv2">
Show this content when Line2 is selected
<div>
<div id="testdiv3" style="display:none">
Show this content when Line3 is selected
<div>

Html

<div class="RadioButton">
<input id="TestRadio_1" type="radio" value="1" name="TestRadio" data-val-required="You must select an option for TestRadio" data-val="true">
<label for="TestRadio_1">Line1</label>
</div>
<div class="RadioButton">
<input id="TestRadio_2" type="radio" value="2" name="TestRadio" checked="checked">
<label for="TestRadio_2">Line2</label>
</div>
<div class="RadioButton">
<input id="TestRadio_3" type="radio" value="2" name="TestRadio" >
<label for="TestRadio_3">Line3</label>
</div>

当我选择radiobutton1,即line1时,我如何类似地显示testdiv1所有的div。

来源:http://jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html

// handle radio group change event
$('input[name="TestRadio"]').on('change', function() {
    // switch on the radio value
    switch(this.value){
         case '1':
             $('[id*="testidiv"]').hide();
             $('#testidiv1').show();
             return;
         case '2':
             $('[id*="testidiv"]').hide();
             $('#testidiv2').show();
             return;
         case '3':
             $('[id*="testidiv"]').hide();
             $('#testidiv3').show();
             return;
    }
});

如果元素之间的关系是1:1,那么使用索引是一种简单而干净的方法

var $radios=$('input[name="TestRadio"]'), $content=$('[id*="testdiv"]');    
$radios.on('change', function() {
    var idx= $radios.index(this);
    $content.hide().eq(idx).show()
});