checkbox not send correct value true or false when click approve button it only working for first time?

Ahmed Salah Abed Elaziz 390 Reputation points
2024-01-20T01:26:18.4366667+00:00

I work on asp.net MVC application I face issue check box yes or no send false value yes or no when click approve button

I have two check box one represent true and second false as user requested and i don't it to be radio button because bossiness user request it . Yes represent true No represent false

I Face Issue when select Yes or no for first time it send value correctly if Yes then true or No then false but when i select Yes or No for second time it not working correctly and send only false to approve button what i try 1 - user UI for Yes or No

 <td style="width: 50%; font-weight: bold; padding-top: 10px;">
      @Html.Label("Did you try to retain the staff?", htmlAttributes: new { @class = "control-label col-md-5" })
      <div class="col-md-7">
          <input type="checkbox" id="RetainStuff" name="RetainStuff" value="true" class="retaindtuff-checkbox" @(Model.RetainStuff == true ? "checked" : "") />
          Yes
          &nbsp;&nbsp;
          <input type="checkbox" id="RetainStuff" name="RetainStuff" value="false" class="retaindtuff-checkbox" @(Model.RetainStuff == false ? "checked" : "") />
          No
      </div>
  </td>
   <a id="approveControlsId" onclick="submit();" class="btn btn-primary" style="min-width: 100px;margin-top:5px;"><i class="glyphicon glyphicon-ok"></i> Approve </a>

2 - when change yes or no check box to get false of retain stuff i use jQuery as below

 $('.retaindtuff-checkbox').on('change', function () {
     $('.retaindtuff-checkbox').not(this).prop('checked', false);
     var selectedValue = $(this).val();
     $('#RetainStuff').val(selectedValue);

 });

3 - when click button approve it call submit function as below

function submit() {
        console.log("check submit");
            var ResignationRequester = new Object();
            ResignationRequester.RequestNo = document.getElementById("RequestNo").innerHTML.trim();
   
  

        var RetainStuffElement = document.getElementById("RetainStuff");

        if (RetainStuffElement) {
           
            var RetainStuffElementExist = document.querySelector('input[name="RetainStuff"]:checked');
          
            if (RetainStuffElementExist && RetainStuffElementExist.value === "false") {
                ResignationRequester.RetainStuff = RetainStuffElementExist.value;
                Swal.fire({
                    icon: 'warning',
                    title: 'Retain Stuff is Empty',
                    text: 'retain stuff comment is empty and retain stuff is No '
                });
                ResignationRequester.RetainStuff = null;
                return false;
            } 
            else if (RetainStuffElementExist) {
                ResignationRequester.RetainStuff = RetainStuffElementExist.value;
               
            } 
            else {
                ResignationRequester.RetainStuff = null;
                Swal.fire({
                    icon: 'warning',

                    title: 'Retain Stuff is Empty',
                    text: 'Retain Stuff Must Not Empty'
                });
                return false;
            }
        }
        else {
            ResignationRequester.RetainStuff = "";

        }
 
            if (ResignationRequester != null) {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("ApprovalIndex", "Resignation")',
                    data: JSON.stringify(ResignationRequester),
                    contentType: "application/json; charset=utf-8",
                    /*dataType: "json",*/
                    datatype: "html",
                    success: function (response) {
                        //console.log(response);

                        window.location.href = '@Url.Action("PendingManagersRequests","Resignation")';
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            }
    }  

4 - action result calling ApprovalIndex on resignation controller [HttpPost] public async Task<ActionResult> ApprovalIndex(ResignationRequester REQ) { //update approve status } so why checkbox yes or no working on first time only Image for page i work on it retainstuff

Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

Accepted answer
  1. Pinaki Ghatak 5,600 Reputation points Microsoft Employee Volunteer Moderator
    2024-01-20T11:38:02.8766667+00:00

    Helo @Ahmed Salah Abed Elaziz The problem appears to be that the checkboxes are not sending the correct values when clicked for the second time. The issue might be related to the fact that you’re using the same id attribute for both checkboxes. In HTML, the id attribute should be unique within a page. You might want to consider using different id attributes for your checkboxes. Also, the ASP.NET MVC’s Html.CheckBoxFor() helper method generates an additional hidden input for each checkbox. This hidden input is causing the “true false” values you’re seeing for each form element. You could try using plain HTML checkboxes instead of Html.CheckBoxFor(). Here’s an example:

    <input type="checkbox" name="RetainStuff" value="true" class="retaindtuff-checkbox" @(Model.RetainStuff ? "checked" : "") /> Yes
    <input type="checkbox" name="RetainStuff" value="false" class="retaindtuff-checkbox" @(Model.RetainStuff == false ? "checked" : "") /> No
    

    In your jQuery code, you’re setting the value of #RetainStuff which is an id shared by both checkboxes. Instead, you should be setting the value of the checkbox that was changed. Here’s an updated version of your jQuery code:

    $('.retaindtuff-checkbox').on('change', function () {
        $('.retaindtuff-checkbox').not(this).prop('checked', false);
        $(this).val(this.checked);
    });
    

    In this code, this.checked will give you the current state of the checkbox that was changed. I hope this helps! Please tag this as answered, if this helps you.


2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-01-20T22:53:36.39+00:00

    your submit code is overly complex, a little hacky. but your real issues is your buggy on change code.

    $('.retaindtuff-checkbox').on('change', function () {
        $('.retaindtuff-checkbox').not(this).prop('checked', false);
        $(this).val(this.checked);
    });
    

    you have two checkboxes, with values "true" & "false". but no matter which one you check, you change its value to true, and if unchecked its value to false. you should just set the checked.

    $('.retaindtuff-checkbox').on('change', function () {
        $('.retaindtuff-checkbox').not(this).prop('checked', !this.checked);
    });
    
    1 person found this answer helpful.

  2. AgaveJoe 30,126 Reputation points
    2024-01-20T15:20:06.6666667+00:00

    I have two check box one represent true and second false as user requested and i don't it to be radio button because bossiness user request it . Yes represent true No represent false

    Radio buttons are the proper solution. It is very unusual for a business owner to restrict what HTML elements are on the page. Usually a business owner simply wants the application to function according to their business rules.

    If appearance is the actual issue then style the radio button appear as checkboxes. If I recall correctly, this was suggested in one of your prior threads too.

    https://stackoverflow.com/questions/279421/can-you-style-an-html-radio-button-to-look-like-a-checkbox The following worked for me. Play with the style to get appearance you want.

    input[type="radio"] {
        appearance: none;
        border: 1px solid #d3d3d3;
        width: 30px;
        height: 30px;
        content: none;
        outline: none;
        margin: 0;
        box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    }
    
    input[type="radio"]:checked {
        appearance: none;
        outline: none;
        padding: 0;
        content: none;
        border: none;
    }
    
    input[type="radio"]:checked::before {
        position: absolute;
        color: green !important;
        content: "\00A0\2713\00A0" !important;
        border: 1px solid #d3d3d3;
        font-weight: bolder;
        font-size: 21px;
    }
    

    The jQuery is very simple because you are using the right HTML element for the use case.

    <div class="col-md-7">
        <label><input type="radio" name="RetainStuff" value="1"> Yes</label>
        <label><input type="radio" name="RetainStuff" value="0"> No</label>
    </div>
    <div>
        <a id="approveControlsId" onclick="submit();" class="btn btn-primary" style="min-width: 100px;margin-top:5px;"><i class="glyphicon glyphicon-ok"></i> Approve </a>
    </div>
    
    @section scripts {
        <script>
    
            function submit() {
                var val = $('input[name="RetainStuff"]:checked').val();
                console.log(val);
            }
        </script>
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.