-1

We have a signup form for existing customers and have all text input fields populating with their information (first name, last name and email address). We also have a list of radio button group with three radio buttons and need to pre-populate (select) the radio button that corresponds with their contact record in our database.

I've mapped their contact record info to a var for this field.

var flavorFave = <span class=dbrecord >Favorite Ice Cream Flavor</span>

Here's the form code for the radio buttons:

<input type="radio" class="custom-control-input" id="Vanilla" name="flavor" value="Vanilla">
<input type="radio" class="custom-control-input" id="Chocolate" name="flavor" value="Chocolate">
<input type="radio" class="custom-control-input" id="Strawberry" name="flavor" value="Strawberry">
...
...
...

How can we configure the form so that the correct radio button is checked if the variable "flavorFave" is defined? For example, if the variable "flavorFave" equals "Vanilla", then we want the "Vanilla" radio button to be checked.

user3120861
  • 177
  • 2
  • 17
  • 1
    You've told us your goal, but what's the issue with it? If you have a specific problem please edit the question to give more details of it, along with any error messages you encounter – Rory McCrossan Aug 26 '19 at 14:52
  • I think you need to check if it it not undefined ? if(typeof flavorFave !== "undefined"){radiobtn = document.getElementById(flavorFave); radiobtn.checked = true; } – Jordi Jordi Aug 26 '19 at 15:33

3 Answers3

0

you'd probably get the data from the database and set the one with the corresponding value to checked with jQuery props

.prop('checked', true);
David Ko
  • 304
  • 1
  • 3
  • 11
0

The following grabs the 'flavor' preference from the database and stores it in a variable called 'flavorFave. The following is proprietary to our system.

var flavorFave = <span class=dbrecord >Favorite Ice Cream Flavor</span>

The source code would show the flavor instead of that span tag, such as this:

var flavorFave = "strawberry";

If the variable 'flavorFave' is not defined, it will default to 'Vanilla'. If the flavor is defined, it will pre-populated the corresponding radio button:

if(flavorFave === ''){  
  $("[name=flavor][value='Vanilla']").prop("checked", true)
} else {
  $("[name=flavor][value=" + flavorFave + "]").prop("checked", true)
  };
});
user3120861
  • 177
  • 2
  • 17
  • 1
    Instead of providing a code-only answer, can you please provide an explanation of how this works? – Wyck Aug 26 '19 at 19:29
0

I think you need to check if it it not undefined ?

if(typeof flavorFave !== "undefined"){ radiobtn = document.getElementById(flavorFave); radiobtn.checked = true; }

Jordi Jordi
  • 461
  • 3
  • 10