user2726041
user2726041

Reputation: 359

if url is equal to radio button value, then check radio button

I have 4 radio button each with a different url value.

I have created this script with jQuery to redirect the browser to the radio button value when checked:

jQuery:

jQuery('#searchfilter input').click(function () {
   if (jQuery('#searchfilter input').is(':checked')) {
      var value = jQuery(this).attr('value');
      window.location.href = value;
   }
});

HTML:

<div id="searchfilter">
   <div class="radio">
      <label>
         <input type="radio" value="url1" name="filter">URL1
      </label>
   </div>
   <div class="radio">
      <label>
         <input type="radio" value="url2" name="filter">URL2
      </label>
   </div>
   <div class="radio">
      <label>
         <input type="radio" value="url3" name="filter">URL3
      </label>
   </div>
   <div class="radio">
      <label>
         <input type="radio" value="url4" name="filter">URL4
      </label>
   </div>                 
</div>

The newly loaded page contains the same four radio buttons. I would like to put a check in the radio button which has the same value as the url. In other words, I'd like the last radio button checked to remain checked.

Is there an lean and efficient way to do this in jQuery without having to run four ifs and set up four variables for the url values?

Upvotes: 1

Views: 1315

Answers (2)

semirturgay
semirturgay

Reputation: 4201

this will do trick:

 $(document).ready(function (){
       $('#searchfilter input').each(function (){
          if($(this).val()==window.location.href){
            $(this).attr("checked","true");
          }
       }); 
})

here a working fiddle

Upvotes: 2

Gjohn
Gjohn

Reputation: 1281

Something like this perhaps - it would loop through all the radio buttons on your form and you are then left with one if statement.

$(document).ready(function() {
      $('input[type=radio]').each(function() {
           if ($(this).prop('value') == window.location))
           {
              $(this).prop('checked', true)
           }
       });
 });

Upvotes: 0

Related Questions