Bruno
Bruno

Reputation: 9027

How to check dynamically checkbox in form if there is a match

I'm using a piece of code to check in a form if a checkbox matches the content of a given variable.

Everything works great but the thing is that I'd like to have this checkbox checked if I have a match but I don't know how to do this.

my javascript code to see if there is a match :

    <script type="text/javascript">

    function loopForm(form,job) {
       var cbResults = 'Checkboxes: ';
       var radioResults = 'Radio buttons: ';
       for (var i = 0; i < form.elements.length; i++ ) {
         if (form.elements[i].type == 'checkbox') {
            if (form.elements[i].id == job) {
                // This works great but I'd like instead to have the element checked
                alert(job);
            }
         }
       }

    }
    var url = window.location.pathname;
    var filename = url.substring(url.lastIndexOf('/')+1);
    var job = filename.split("-");
    var metier = job[0];
    loopForm(document.formulaire,metier);
    </script>

Upvotes: 0

Views: 1693

Answers (2)

Reporter
Reporter

Reputation: 3948

just

form.elements[i].checked = true;

Upvotes: 1

I82Much
I82Much

Reputation: 27326

if (form.elements[i].id == job) {
    form.elements[i].checked = true;
}

Upvotes: 1

Related Questions