0

Trying to set Radio button in Update form

when user clicks update/edit button, a new window opens and loads the previous values that user entered in the respective elements with the radio buttons checked/set to the previous values but no radio buttons are selected

It is multiple choice question type with 6 options and user selects 1 out of them trying to set with name (as ID's are unique to all the radio buttons in the group) but not solved

enter code here

//this code works in console:

$('#inlineRadio1_1').attr('checked', true);

// but the below code does not when trying to set/check radio button

var SetRadio1; //previous radio button value in the variable SetRadio1 from 1 to 6
if (SetRadio1 == 1) {
$('#inlineRadio1_1').attr('checked', true);
}
else if (SetRadio1 == 2) {
$('#inlineRadio1_2').attr('checked', true);
}

else if (SetRadio1 == 6) {
$('#inlineRadio1_6').attr('checked', true);

}


<div class="col-md-12 pb-4">
                  <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="inlineRadio1_1" value="1">
                    <label class="form-check-label" for="inlineRadio">1</label>
                  </div>
                  <div class="form-check form-check-inline px-1">
                    <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="inlineRadio1_2" value="2">
                    <label class="form-check-label" for="inlineRadio">2</label>
                  </div>
                  <div class="form-check form-check-inline px-1">
                    <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="inlineRadio1_3" value="3">
                    <label class="form-check-label" for="inlineRadio">3</label>
                  </div>
                  <div class="form-check form-check-inline px-1">
                    <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="inlineRadio1_4" value="4">
                    <label class="form-check-label" for="inlineRadio">4</label>
                  </div>
                  <div class="form-check form-check-inline px-1">
                    <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="inlineRadio1_5" value="5">
                    <label class="form-check-label" for="inlineRadio">5</label>
                  </div>
                  <div class="form-check form-check-inline px-1">
                    <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="inlineRadio1_6" value="6">
                    <label class="form-check-label" for="inlineRadio">6</label>
                  </div>
                </div>
```````````````````````````````````
$.ajax({
      url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('SharePointList')/items?$filter=ID eq " + ID_number,
      type: "GET",
      async:false,
      headers: {
        "accept": "application/json;odata=verbose",
      },
      success: function (data) {

$("#Cars").val(data.d.results[0]["Car"]); //text area, works
$("#Books").val(data.d.results[0]["Book"]);  //text area, works
$('input[name=inlineRadioOptions1][value=' + data.d.results[0]["Score_x0020_Q1"] + ']').prop('checked','checked'); //does not work
$('input:radio[name="inlineRadioOptions1"]').attr('checked', true); //does not work
$('#inlineRadio1_1').attr('checked', true); //by ID, works when tried in console
 },
      error: function (error) {
        alert(JSON.stringify(error));
      }
    });
  • "*a new window opens and loads the previous values*" - how are the previous values loaded? HTTP is stateless, which means the "state" (this includes any variables you set in JS) from one page is not available to the next page. You need to use something like a query string, or cookies, sessions, local storage, or something on the back end (eg PHP etc) generating your pages using previously submitted data. See eg https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads – Don't Panic Jan 01 '22 at 23:49
  • Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – Don't Panic Jan 02 '22 at 22:04
  • The previous values of the radio buttons are loaded from a SharePoint list using get method (ajax query) – Random Stuff Jan 03 '22 at 08:20
  • OK; since you didn't mention that in your question, the answers and hints you have so far are not so useful, I guess. Can you create a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve) which demonstrates the problem? – Don't Panic Jan 03 '22 at 08:58
  • Please take a look if you can help with this code – Random Stuff Jan 03 '22 at 16:29
  • [I created a simplified version of your code](https://jsfiddle.net/dont_panic/95z23x6c/), with a faked AJAX and faked response data, and it works fine. Ignore the fake AJAX stuff, that's just how you simulate an AJAX call on JSFiddle - the imporant thing is the success function runs, asynchronously like AJAX should, and uses the faked response data we send it to do the actions you're trying to do. The first approach, using `.prop()`, works fine. The 2nd approach does not make sense, since it does not specify *which* radio to tick - they *all* match that name. And the 3rd also works fine. – Don't Panic Jan 03 '22 at 22:50
  • Is the AJAX response really in the format you are expecting? Does `data.d.results[0]["Score_x0020_Q1"]` really exist, and is it what you exepct? Check your browser's devtools, any errors on the console? On the network tab, click the request, is the right data being sent to the server, and does the server respond OK, with the payload you expect? – Don't Panic Jan 03 '22 at 22:56
  • data.d.results[0]["Score_x0020_Q1"] Yes it exists and get the correct value I finally got it right setradiobuttons1(data.d.results[0]["Score_x0020_Q1"]); inside ajax request and declared a function setradiobuttons1(btn_val1) outside the ajax function setradiobuttons1(btn_val_1){ if(btn_val_1==6){ $('#inlineRadio1_6').attr('checked', true); }else if ------ also the page was loaded before the script is executed as suggested by someone on the internet(moved html code before script code) and now it works Thanks :) – Random Stuff Jan 04 '22 at 03:40

1 Answers1

0

Lets suppose we have this structure and using the script included,everytime we click on a radio button we store its id to localStorage,and next time the page is loaded,the forEach loop will compare every radio id with the stored id,and when it finds it,makes it the selected one.

LocalStorage is one of the methods we can persist our data,the easiest one,but usefull only for storing small amounts of data (i think 5mb is the limit) and only locally,meaning you will be able to access it only in this particular system (and browser),if you clear browser's cache,you also clear localStorage data.

If you need this data accesible across the web,you should start learning how to use databases.

<!DOCTYPE html>
<html lang="en">
<body>
<input type="radio" id="radio1" name="radio" onclick="storeSelectedRadio(this)">
<label for="radio1">radio1</label><br>
<input type="radio" id="radio2" name="radio" onclick="storeSelectedRadio(this)">
<label for="radio2">radio2</label><br>
<input type="radio" id="radio3" name="radio" onclick="storeSelectedRadio(this)">
<label for="radio3">radio3</label><br>
<input type="radio" id="radio4" name="radio" onclick="storeSelectedRadio(this)">
<label for="radio4">radio4</label><br>
<input type="radio" id="radio5" name="radio" onclick="storeSelectedRadio(this)">
<label for="radio5">radio5</label><br>
<input type="radio" id="radio6" name="radio" onclick="storeSelectedRadio(this)">
<label for="radio6">radio6</label><br>
<script defer>

function storeSelectedRadio(e){
localStorage.setItem("selectedRadio", e.id );
}

const selectedRadio = localStorage.getItem("selectedRadio");
    
document.querySelectorAll('input[type="radio"]').forEach(radio =>{
    
if ( radio.id === selectedRadio ){
radio.checked = true;
}
    
})
</script>
</body>
</html>

Next time you should provide your own structure though,and a reproducible example.

Vaggelis
  • 912
  • 5
  • 17
  • Sorry I did not mention all the required details The previous values of the radio buttons are loaded from a SharePoint list using get method (ajax query) Thank You for your help Vaggelis – Random Stuff Jan 03 '22 at 08:17