简体   繁体   中英

Selected value of Radio Button doesn't change

In the view, I have these two radio buttons:

@Html.RadioButtonFor(c => c.CampaignType, "Exclusive")<label>Exclusive</label>
@Html.RadioButtonFor(c => c.CampaignType, "Shared")<label>Shared</label>

The value for Model.CampaignType is set in the controller before the page loads. All of this works fine. If Exclusive is what's saved in the DB, then we get this rendered in the HTML:

<input checked="checked" id="CampaignType" name="CampaignType" type="radio" value="Exclusive"><label>Exclusive</label>
<input id="CampaignType" name="CampaignType" type="radio" value="Shared"><label>Shared</label>

So far, all's well.

But, inside an onclick() event for a button, if I do this:

var values = 
    {
        "CampaignType": $('#CampaignType').val()
    }
alert(values.CampaignType);

The alert always comes up as `Exclusive', even if I have changed the selection to 'Shared'.

What do I need to do so that values.CampaignType reflects the what is selected on the page, and not what was set when the page was loaded?

So you can do start with these:

  1. Remove the invalid id s - multiple id s are invalid in CSS. For getting the value of the checked radio button you can use:

     $('input[name=CampaignType]:checked').val() 

    or

     $('input[type=radio]:checked').val() 
  2. For the label to work you have to link it with the corresponding radio button using the for attribute.

See demo below:

 function submit() { var values = { "CampaignType": $('input[name=CampaignType]:checked').val() } console.log(values.CampaignType); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input checked="checked" id="CampaignType1" name="CampaignType" type="radio" value="Exclusive"> <label for="CampaignType1">Exclusive</label> <input id="CampaignType2" name="CampaignType" type="radio" value="Shared"> <label for="CampaignType2">Shared</label> <br/> <button onclick="submit()">click here</button> 

All the best!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM