L.fcg
L.fcg

Reputation: 167

How to set default values/placeholders for depended select lists?

I have four depended select lists and I want to give all the select lists a default value/placeholder like this: select .... The problem is that when I try to do it like this: <option value=""> Select ... </option> it doesn't work. Because when I change the first select list the other select lists gets automically changed because of the dependency.

This is how I'm filling my depended select lists:

    $("#slctTable").change(function()
    {
        $.getJSON("dropdown_code/get_fields.php?table=" + $(this).val(), success = function(data)
        {
                optionsFields= "";
        for(var i = 0; i < data.length; i++)
            {
                optionsFields += "<option value='" + data[i]['field_name'] + "'>" + data[i]['field_alias'] + "</option>";
            }
        $("#slctField").html("");
        $("#slctField").append(optionsFields);
        $("#slctField").change();
        })
    });   
    });

Whit this function I'm putting the optionsFields into an array:

function allValues(el) {
  var arr = $('option', el).map(function(i, v) {
    return this.value;
  }).get();

  return arr;
}

Upvotes: 0

Views: 69

Answers (2)

Aman Chhabra
Aman Chhabra

Reputation: 3894

It will be great if you can share the exact fiddle, but looking onto your javascript, I can see one issue.

Instead of calling:

 $("#slctTable").change();

I think you should call

 $("#slctTable").trigger("change");

to trigger the change event

Also, its better to have a default string which has the value

<option value="">Select...</option>

Further to this, it will be great if you can create a generic function which can create option strings from the provided array and also can append default option as well in that string. In that case, it will reduce the chances of fault, like the way we have here.

Hope that helps.

Upvotes: 0

Elmer Dantas
Elmer Dantas

Reputation: 4869

instead of optionsFields= ""; use optionsFields= "<option value='0'> Select... </option>". it's not working because you're probably setting your default value in HTML and overwriting it in your change function.

Upvotes: 1

Related Questions