Skip to main content

Dynamically Adding Dropdown Options and Handling "Other" with Show/Hide Functionality

Dropdown menus are a crucial part of many web forms, providing users with predefined options to choose from. However, there are scenarios where users need to add new options or input custom values. This post outlines how to dynamically add options to a dropdown list using a text box and show or hide the text box when "Other" is selected.

Dynamic Dropdown Option Addition

Using JavaScript and Ajax, you can create a seamless experience for users to add new options dynamically. Below is the implementation:

JavaScript Code for Dynamic Option Addition

$(document).on('click', '.btcl', function() {
    var dataString = 'Rule=comp_list';
    $.ajax({
        type: "POST",
        url: "ajax.php",
        data: dataString,
        cache: false,
        success: function(data) {
            $("#company_list").html(data);
        }
    });
});

This function fetches the updated dropdown list dynamically when triggered.

Show/Hide Text Box on "Other" Selection

When the user selects "Other" from the dropdown, a text box appears, allowing them to input a custom value.

JavaScript Code for Show/Hide Functionality

$(document).on('change', '#enq_company', function(e) {
    var t = e.target.type;
    var val = $(this).val();
    if (val === "new" || t === "text") {
        var dataString = 'val=' + val + '&Rule=ins_comp';
        $.ajax({
            type: "POST",
            url: "ajax.php",
            data: dataString,
            cache: false,
            success: function(data) {
                $("#company_list").html(data);
            }
        });
    }
});

This function dynamically updates the dropdown or displays the text box based on the selected option.

HTML Structure for Dropdown

The HTML structure includes a dropdown list with an "Other" option for custom inputs:

<select name="enq_company" id="enq_company" style="width: 310px" required>
    <option value="">Select Company Name</option>
    <option value="1">Google</option>
    <option value="2">Yahoo</option>
    <option value="3">Amazon</option>
    <option value="4">Flipkart</option>
    <option value="new">Other</option>
</select>

PHP Logic in Ajax File

The PHP code processes the dynamic requests and returns either the updated dropdown or the text box for custom input.

Code for Dropdown Update

if (!empty($_REQUEST['Rule']) && $_REQUEST['Rule'] == "comp_list") {
    echo '<select name="enq_company" id="enq_company" style="width: 310px" required>';
    echo '<option value="">Select Company Name</option>';
    dropdown('hmp_companies', 'comp_id,comp_name', 'comp_status=1 order by comp_name', @$insid);
    echo '<option value="new">Other</option>';
    echo '</select>';
}

Code for Text Box Handling

else if (!empty($_REQUEST['Rule']) && $_REQUEST['Rule'] == "ins_comp") {
    $val = secure($_REQUEST['val']);
    if ($val == 'new' || empty($val)) {
        echo '<input name="enq_company" id="enq_company" type="text" placeholder="Enter New Company Name" required>';
        echo '<a href="#x" class="icn-link-blue tooltip btcl" title="Back to Companies List">';
        echo '<i class="fa fa-refresh fa-lg" aria-hidden="true"></i>';
        echo '</a>';
    } else {
        $results = get_data("hmp_companies", "count(*) as cnt,comp_id", "comp_name ='" . $val . "'");
        if ($results[0] > 0) {
            $insid = $results[1];
        } else {
            // Insert new company logic
        }
    }
}

Benefits

  1. User-Friendly: Allows users to add custom values without navigating away from the form.
  2. Dynamic Updates: Fetch updated dropdown options instantly using Ajax.
  3. Flexible Functionality: Handles multiple use cases seamlessly.

Conclusion

This technique simplifies managing dropdowns while providing users with flexibility for custom inputs. Whether you're designing registration forms or complex dashboards, these approaches ensure scalability and an improved user experience.


Comments