简体   繁体   中英

automatically setting a radio button in a group to selected upon returning to a page - how to do?

I have a quick question regarding radio buttons, and how to set them when a user returns to a page. What I now want is to be able to show the item selected, when they RETURN to the page. There are several in the same group, so I can't use getElementByID (sadly!).

This is my HTML:

<input id="q1input" onblur="saveItemData(this.id)" type="radio" name="optradio" value="1 cardiovascular system">cardiovascular system

<input id="q1input" onblur="saveItemData(this.id)" type="radio" name="optradio" value="2 respiratory system">respiratory system

I have some code which successfully gets the checked items value:

var inputData = $("input:radio[name=optradio]:checked").val();

Then, I have the code which is called on reload:

var itemToCheck = document.getElementById(elementID).getAttribute("value", cleanedText);

itemToCheck.checked = true;

How can I target the item which was selected, then set it's checked value to true?

Hope that makes sense.

You can select a specific input type having certain value using:

$('input[type="radio"][value="your_value"]')

In your case try this:

 $(document).ready(function(){ $('input[type="radio"][value="2"]').attr('checked', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" value="1">One <input type="radio" value="2">Two 

Instead of hard code value, you can pass variable like:

var value = 2; 
$('input[type="radio"][value="' + value + '"]') 

if you want to store the selected value and show that value which was selected you can use localStorage for that and store the value there and show it later when the page loades.

$(document).ready(function(){

   $("input[name='optradio']").change(function(){
      var val = $(this).val();
      window.localStorage.removeItem('optradio_value');
      window.localStorage.setItem('optradio_value',val);
   });


    var saved_value = window.localStorage.getItem('optradio_value');

    if(saved_value)
    {
      $("input[name='optradio']").attr('value',saved_value).attr('checked',true);
    }
});

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