TransWikia.com

Check a radio button from data saved in localstorage in a specific form, with a specific name and value

Stack Overflow Asked by B Jarvis on August 31, 2020

I have the following html:

<form class="questionnaire" name="X">
        <table>
            <tr>
                <td>1. text</td>
                <td><label><input type="radio" name="q1" value="B" >Yes     </label><label><input type="radio" name="q1" value="C" >No </label></td>
            </tr>
            <tr>
                <td>2. text</td>
                <td><label><input type="radio" name="q2" value="B" >Yes     </label><label><input type="radio" name="q2" value="C" >No </label></td>
            </tr>

I have saved in localstorage the form name (‘X’), the input type (radio), the input name (‘q1’), and the input value (‘B’) for example, and I am trying to ensure that on a page refresh the form is repopulated so the user doesn’t lose their input. So far I have the following code to to set the radio buttons to checked but I keep getting a ‘is not a function’ error:

function populateFormInput(key, val) {
    var keyParts = key.split('|');
    var inputForm = keyParts[0];
    var inputType = keyParts[1];
    var inputName = keyParts[2];

    if (inputType === 'radio') {
        $('form[name="inputForm"] input[name="inputName"][value="val"]').prop('checked', true);
    }
}

I can’t edit much of the html, though I could give the form an ID if that would help things?

Thanks in advance!

One Answer

You can pass variables into the selector like follows:

$('form[name="' + form_name + '"] input[name="' + field_name + '"][value="' + field_value + '"]').prop('checked', true);

You can change the variable names around to fit your loop, but this will point you into the right directions.

Correct answer by imvain2 on August 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP