Dropdown Input will not let me set a default option or empty select input

I am building a form and using the dropdown select input option. I want the default option to be set to empty so that the customer using this form is required to select an option rather than it loading the page with one already pre-selected. I attempted to put “Select a contact” in the “Default Value” section, but nothing happens.

Hello @seodom,

Welcome to the builder.io forum post.

While there’s no direct way to add a default option or an empty select input, you can achieve this using custom JavaScript code. In the Builder editor, under the “Data” tab → “Edit Content JS + CSS” section, you can utilize the following code to add a default select option:

  setTimeout(function() {
    // Query the select element by its name attribute
    var selectElement = document.querySelector('select[name="contact"]');
    
    console.log(selectElement); // Output the select element to console
    
    if (selectElement) {
      // Create a default option
      var defaultOption = document.createElement("option");
      defaultOption.text = "Select a contact*";
      defaultOption.value = "";
      defaultOption.selected = true; 
      // Add the default option to the select element
       selectElement.insertBefore(defaultOption, selectElement.firstChild);
    } else {
      console.error('Select element not found.');
    }
  }, 1000); // 1000 milliseconds = 1 second


Thank you @manish-sharma for this response! I implemented the code in the JS+CSS section but nothing has changed on the form. Does it look like I did something wrong?



Hello @seodom,

It appears that the “Name*” field has an uppercase “Contact” label, but in your code, you are targeting (‘select[name=“contact”]’). Please adjust this to (‘select[name=“Contact”]’) and see if it resolves the issue.

Thanks,

That worked @manish-sharma ! Another question, The “Select a Contact*” shows up twice now. Is there a way to just show it once? The form also doesn’t recognize that the user hasn’t selected a contact from the drop down. Is it possible for the default contact we set up in the code to trigger the form to realize that nothing has been chosen by the user?

Hello @seodom,

Remove the Default value input from the Dropdown component, which will show only one “Select a Contact*”. For form submission to consider the default input as null, consider using the custom JS option to validate the form dropdown before submitting.