Yogi Bear Yogi Bear - 6 months ago 81
Javascript Question

without an event for a radiobutton or checkbox, how can I set it true or false programmatically

I have a page with radiobuttons and checkboxes; the form has previously been filled out by the user. I need to bring the form back up for them to edit the EXISTING data, which means I have to programmatically check checkboxes and check radio buttons.

If I HAD an event, I could easily change the corresponding control with srcElement, but there is no event in this case. I haven't been able to find a way with document.getElementById('XXX'). ??? to work in any way.

Using Angular 4 if that helps.

Thoughts?

Thanks in advance, :-)

Answer Source

Use data binding. Then you can set the changed value and the checkbox and radio buttons will check/select automatically.

Here is an example:

                    <label>
                        <input id="sendCatalogId"
                               type="checkbox"
                               [(ngModel)]="sendCatalog"
                               name="sendCatalog" >
                        Send me your catalog
                    </label>

And a radio button:

                            <label class="radio-inline">
                                <input type="radio" id="addressType1Id" value="home"
                                       [(ngModel)]="addressType"
                                       name="addressType">Home
                            </label>
                            <label class="radio-inline">
                                <input type="radio" id="addressType1Id" value="work"
                                       [(ngModel)]="addressType"
                                       name="addressType">Work
                            </label>
                            <label class="radio-inline">
                                <input type="radio" id="addressType1Id" value="other"
                                       [(ngModel)]="addressType"
                                       name="addressType">Other
                            </label>

This in the component class:

...
export class CustomerComponent  {
    sendCatalog = false;
    addressType = "home";

    constructor() {
        sendCatalog = true;
        addressType = "work";
    }
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download