Search code examples
htmljqueryradio-button

Why jQuery returning value of radio buttons as "ON"? How to correct it?


I'm not absolutely novice but somehow it's caught me since an hour. Can you please help me by finding where I am making a mistake in the following piece? I'm trying to return value of the "checked/selected" Radio option and it is returning "on" every time.

My (Bootstrap) HTML Code:

<div class="form-row mb-4 p-2 text-center font-weight-bold rounded-top shadow-sm-dark no-shadow-hover bl__home_apr-choice">
    <div class="col-4 offset-2 col-md-3 offset-md-0 mb-md-0 mb-1">
      <div class="custom-control custom-radio custom-control-inline">
        <input type="radio" id="searchByProject" name="searchBy" class="custom-control-input" checked="checked">
        <label class="custom-control-label" for="searchByProject" value="Project" pointer>by Project</label>
      </div>
    </div>
    <div class="col-4 col-md-3 offset-md-0 mb-md-0 mb-1">
      <div class="custom-control custom-radio custom-control-inline">
        <input type="radio" id="searchByInvoiceID" name="searchBy" class="custom-control-input">
        <label class="custom-control-label" for="searchByInvoiceID" value="Invoice" pointer>by Invoice</label>
      </div>
    </div>
    <div class="col-4 offset-2 col-md-3 offset-md-0 mb-md-0">
      <div class="custom-control custom-radio custom-control-inline">
        <input type="radio" id="searchByStartDate" name="searchBy" class="custom-control-input">
        <label class="custom-control-label" for="searchByStartDate" value="Started" pointer>by Start Date</label>
      </div>
    </div>
    <div class="col-4 col-md-3 offset-md-0 mb-md-0">
      <div class="custom-control custom-radio custom-control-inline">
        <input type="radio" id="searchByEndDate" name="searchBy" class="custom-control-input">
        <label class="custom-control-label" for="searchByEndDate" value="Ended" pointer>by End Date</label>
      </div>
    </div>
  </div>

And this is how I am using jQuery:

console.log($('input[name=searchBy]:checked').val()); 

Any help will be highly appreciated. Thanks in advance.


Solution

  • You should set the value in the input tag, you're doing it in the label.


    Your radio should be like this:
    <input type="radio" id="searchByEndDate" name="searchBy" value="Ended" checked>