0

This is my html code.

<form id="item">
<div class="form-group col-lg-3 col-md-3 col-sm-3 col-sx-3">
     <label for="itemtype">Hotel</label>
     <input type="radio" class="radio" id="itemtype" name="optradio" value="H" checked>
     <label for="itemtype">AirPort</label>
     <input type="radio" class="radio" id="itemtype" name="optradio" value="A">
</div>
</form>

And this is my jquery.

function save() {
    debugger

    $.ajax({
        type: "POST",
        data: { "item": { "itemid": $("#itemid").val(),  "itemtype": $('#itemtype').val() }},
        url: "@Url.Action("Save", "Item")",
        cache:false,
        success: function (data) {
            debugger
            if (data.isSuccess) {
                alert("Saved Succesfully!");
                window.location.href = "@Url.Action("Index", "Item")";
            }
        }, error: function (err) {
            alert("Saved Failed!")
            debugger
        }
});
}

All the time when I trying to save the item type call "A", it never happen. Always this query getting radio button value as "H". I need to pass the 2nd value "A".

Stefan
  • 652
  • 5
  • 19
  • 1
    just change your second radio button id, and try to access using new id. you will always get first control value if you use same id for multiple controls. – Vishal modi Oct 21 '19 at 11:37
  • Having the same id on two elements is not good practice, and if you want the "A" send as value it must have "checked" property. – Yecodeo Oct 21 '19 at 11:39
  • Better still, remove the id attribute if you are not doing anything with it on client side. – codein Oct 21 '19 at 11:41

2 Answers2

2

You can get the correct value by using the name, please remove the duplicate id

$('input[name=optradio]:checked', '#item').val()
pbachman
  • 934
  • 2
  • 11
  • 18
0
$('input[name=optradio]:checked').val();

it is not recommended to have two identical ids on one page


other solution using class name:

<form id="item">
<div class="form-group col-lg-3 col-md-3 col-sm-3 col-sx-3">
     <label for="itemtype">Hotel</label>
     <input type="radio" class="radio itemtype" name="optradio" value="H" checked>
     <label for="itemtype">AirPort</label>
     <input type="radio" class="radio "itemtype" name="optradio" value="A">
</div>
</form>
$('.itemtype:checked').val();

In jquery the best way to send data form a formular is to use serialize() or serializeArray() methods.

Some exemple : serialize-form-data-to-json

Tohm
  • 305
  • 1
  • 5