Dynamically changing dropdown to textfield opencart

394 Views Asked by At

I am trying to change a drop down so that a user can add a custom input instead. I am using VQMod and have currently set up a PHP array as follows:

<td><select name="electricColours">
               <?php foreach (array("", "White", "Black", "Add Custom Colour..." ) as $eColours) { ?>
                 <?php if ($electricColours == $eColours) { ?>
                  <option value="<?php echo $eColours;?>" selected="selected"><?php echo $electricColours; ?></option>
                 <?php } else { ?>
                   <option value="<?php echo $eColours;?>"><?php echo $eColours; ?></option>
                 <?php }?>
              <?php } ?>
              <td class="left"><a onclick="AddCustomColour();" class="button"><?php echo "Add Custom Colours"; ?></a></td>
              </select>

How would I be able to add new values to the eColours using the "Add Custom Colour..." so that the user inputs something and that colour is added on to the array.

I thought using Javascript so that it shows up as an alert and the user gets to choose their option would work however it keeps saying the variable is not defined.

<SCRIPT TYPE="text/javascript">
                function AddCustomColour()
                {
                    var colour=prompt("Please add custom colour","Silver");
                    var arrays =  <?php echo json_encode($electricColours); ?>;
                    if (colour!=null)
                    {
                        electricColours.push(colour);
                    }
                }
        </SCRIPT>

Thanks

2

There are 2 best solutions below

0
On

Use the DOM API:

var option = document.createElement("option");
option.setAttribute("value", value);
option.appendChild(document.createTextNode(value));
document.getElementById("the_select_element").appendChild(option);

Instead of:

document.getElementById("the_select_element")

You could do something like:

document.forms.the_form.electricColours
4
On

replace this code

<SCRIPT TYPE="text/javascript">
                function AddCustomColour()
                {
                    var colour=prompt("Please add custom colour","Silver");
                    var arrays =  <?php echo json_encode($electricColours); ?>;
                    if (colour!=null)
                    {
                        electricColours.push(colour);
                    }
                }
        </SCRIPT>

With this Code

<script type="text/javascript">
function AddCustomColour()
{
    var colour=prompt("Please add custom colour","Silver");
    var ob = $("#electricColours");
    if (colour!=null)
    {
        ob.prepend("<option value="+ val +">" + text + "</option>");

    }
}
</script>