Search code examples
javascriptjquerydrupaldrupal-webform

Change Webform hidden values via Javascript


I've created a Drupal site in which I'm including an external PHP file and an external JS. They both seems to work.

Then I added a webform which contains some hidden fields. One of the functions of the JS has to change these hidden fields value. On page source code I saw these fields are named "submitted[comp_name]" where comp_name is the name of the specific field, as defined in webform.

The JS function has 2 input formal parameters, one is comp_name and the other is id. The purspose is to set the id value to the comp_name field.

I tried:

document.getElementByName("submitted["+comp_name+"]").value = id;

and also

$("#submitted["+#comp_name#+"]").val(id);

but when I try to send the webform, the hidden values remains the same as default.

What I am doing wrong? Is it possible to change webform hidden value via javascript??


Solution

  • It seems submitted["+comp_name+"] is the name of your element, but in javascript we don't have document.getElementByName, but you can do it like:

    document.querySelector("input[name='submitted["+comp_name+"]']").value = id;
    

    or using jQuery do:

    $("input[name='submitted["+comp_name+"]']").val(id);
    

    but if submitted["+comp_name+"] is the id do this:

    document.getElementById("submitted["+comp_name+"]").value = id;
    

    or using jQuery:

    $("#submitted["+comp_name+"]").val(id);