0

Please how can I populate combo box based on input value from textbox using HTML/PHP

E.g. *if textbox value equals "a" then combo box value equals (a,b,c,d) else if textbox value equals "b" then combo box value equals (e,f,g,h)

any help is highly welcome

2
  • do it with jquery (client side). php has nothing to do with this because it's a server side programming language. you may want to read programmers.stackexchange.com/a/171210/35031 Commented May 1, 2016 at 22:26
  • @PedroLobito but I still need a sample code Commented May 1, 2016 at 22:36

2 Answers 2

2

this script will do it.

    $("#TextInputID").change(function(){

    var optionsForA = ['a','b','c','d'];
    var optionsForB = ['e','f','g','h'];
    var options = '';

    var inputVal = $("#TextInputID").val();
    switch(inputVal) {
        case "a":
            for (var i=0;i<optionsForA.length;i++){
            options += '<option value="'+ optionsForA[i] + '">' + optionsForA[i] + '</option>';
            }
            break;
        case "b":
            for (var i=0;i<optionsForB.length;i++){
            options += '<option value="'+ optionsForB[i] + '">' + optionsForB[i] + '</option>';
            }
            break;
    }

    $('#comboboxid').find('option').remove().end().append(options);
});
Sign up to request clarification or add additional context in comments.

3 Comments

is not clearing the previous value on it is just appending the value
good point! I've updated the script to remove the previously existing values. check changes in the lat line from $('#comboboxid').append(options); to $('#comboboxid').find('option').remove().end().append(options);
good one but still selecting the first value, all the way thanks
1

It's fairly simple and easy. There are two ways of doing it

  1. Either do it on client side using javascript/jQuery by putting an onchange listener on the textbox each time it's value is changed check if it's a then place specific options in combobox, if it's b put other concerned options in combobox and so on ...

  2. You can do it using PHP and AJAX as well, if textbox has a value like 'a' so truncate comboxbox options and using ajax fetch certain options from the database and append them to the comboxbox.

Need more explanation? hit me back :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.