vendredi 25 septembre 2020

Checking checkboxes from colon-delimited string

Our online form receives a colon-delimited string from the database for one of our fields. For example, we have a checkbox group called "Favorite Fruits", which contains eight checkboxes:

 Apples - AP
 Bananas - BA
 Blueberries - BL
 Cherries - CH
 Grapes - GR
 Oranges - OR
 Raspberries - RA
 Strawberries - ST

Let's say a user submits a form with three checkboxes checked: Cherries, Grapes and Strawberries. When users submit the form, the 'fruits' field receives the following: CH,GR,ST. When the user revisits the page, instead of comma-separated, it's received like this CH::GR::ST. For this example, I'm trying to figure out how to check the checkboxes so that Cherries, Grapes and Strawberries are checked on page load.

Here's what I have so far:

   <div id='fruits'>
    <input type='checkbox' id='AP' value='Apples' />Apples<br />
    <input type='checkbox' id='BA' value='Bananas' />Bananas<br />
    <input type='checkbox' id='BL' value='Blueberries' />Blueberries<br />
    <input type='checkbox' id='CH' value='Cherries' />Cherries<br />
    <input type='checkbox' id='GR' value='Grapes' />Grapes<br />
    <input type='checkbox' id='OR' value='Oranges' />Oranges<br />
    <input type='checkbox' id='RA' value='Raspberries' />Raspberries<br />
    <input type='checkbox' id='ST' value='Strawberries' />Strawberries<br />
   </div> 

    var faveFruits = ['CH','GR','ST'];

    $("#fruits").find('[id=' + faveFruits.join('], [id=') + ']').prop("checked", true);

That works fine, because of the way the faveFruits variable/array is defined. It actually loads on the page like this:

    var faveFruits = CH::GR::ST

https://jsfiddle.net/Codewalker/mw9746pq/12/




Aucun commentaire:

Enregistrer un commentaire