Question

I have some scripts where I want to update a div when a radio button is changed. Further more I store the value of the selected radio in a sessionStorage, so that the according radio button stays selected when the page is visited again.

My problem is, that if I use my sessionStorage script and my update script, the update script doesn't work anymore and just keeps the value stored in the session.

I mean this line particularly:

inhalt_time = $("input[type='radio'][name='chooseTime']:checked").val();

If I remove that line:

$("input[type='radio'][name='chooseTime']").val(chosen_time).prop('checked', true);

the update script works again.

Does anyone know how to avoid this conflict?

Here is my html:

<div class="chooseTime">
   Bitte w&auml;hlen Sie ihr gew&uuml;nschte Lieferzeit.
   <label class="radio">
      <input type="radio" name="chooseTime" value="06:00 Uhr - 10:00 Uhr" />
      06:00 Uhr - 10:00 Uhr
   </label>
   <label class="radio">
      <input type="radio" name="chooseTime" value="10:00 Uhr - 14:00 Uhr" />
      10:00 Uhr - 14:00 Uhr
   </label>
   <label class="radio">
      <input type="radio" name="chooseTime" value="15:00 Uhr - 17:00 Uhr" />
      15:00 Uhr - 17:00 Uhr
   </label>
</div>

My jquery for the update:

$('.chooseTime').on('change', 'input[type=radio]', function() {
     updateAnzeige();
});

function updateAnzeige() {
    inhalt_time = $("input[type='radio'][name='chooseTime']:checked").val();
    if(inhalt_time === undefined) {
        inhalt_time = "<span class='red'>Bitte wählen Sie eine gewünschte Lieferuhrzeit aus.</span>";
    }
    $('.anzeige').html(inhalt_time);            
}

My jquery for the sessionStorage:

if(sessionStorage.getItem("lieferzeitpunktart") == "Custom") {
    chosen_time = sessionStorage.getItem("lieferzeitpunkt_time");
    $("input[type='radio'][name='chooseTime']").val(chosen_time).prop('checked', true);
}
Was it helpful?

Solution

Doh!! The answer is so simple.

By using .val(chosen_time) in $("input[type='radio'][name='chooseTime']").val(chosen_time).prop('checked', true); I gave each radio button the same value instead of checking for the radio with the value I was looking for..

The correct line of code is of course:

$("input[type='radio'][name=chooseTime][value='"+chosen_time+"']").attr('checked', true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top