How to get value from a Radiobutton field in JS?

Asked

Viewed 301 times

0

I can’t get the value of my field RadioButton

@Html.Label("Ativo")
@Html.RadioButtonFor(v => v.Ativo,"S", new { name="ativo"})
@Html.Label("Inativo")
@Html.RadioButtonFor(v => v.Ativo,"N", new { name="ativo"})

<script>
function ObterValues() {
 var radioButton =  $('input:radio[name^=ativo]:checked').val();  
 console.log(radioButton);
}
 </script>
  • $('[input type="radio"][name="active"]:checked'). val(); Try this; NOTE: NOT TESTED

1 answer

2

The problem here is in the MVC syntax. To overwrite the attribute name html, you need to use the @Name (with N maisculo).

Dotnetfiddle

Model

using System;
using System.ComponentModel.DataAnnotations;

namespace HelloWorldMvcApp
{
    public class SampleViewModel
    {
        [Display(Name="Ativo")]
        public bool Ativo { get; set; }
    }
}

Controller

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace HelloWorldMvcApp
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View(new SampleViewModel());
        }
    }
}

View

@model HelloWorldMvcApp.SampleViewModel
@{
    Layout = null;
}

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head> 
    <body>
        @using (Html.BeginForm())
        {
            <div>
                @Html.Label("Ativo")
                @Html.RadioButtonFor(v => v.Ativo,"S", new { @Name="ativo"})
                @Html.Label("Inativo")
                @Html.RadioButtonFor(v => v.Ativo,"N", new { @Name="ativo"})
            </div>
        }
        <!-- JS includes -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script type="text/javascript">
            $(function(){           
                var ativo = $("input:radio[name='ativo']");
                function onAtivoClick() {
                    var value =  ativo.filter(":checked").val();
                    console.log(value);
                }                   
                ativo.click(onAtivoClick);
            });
        </script>
    </body>
</html>
  • blz !! had success!! Obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.