Search code examples
jqueryselectchained

Jquery chained select box, how to disable blank option


<select id="countryselect" name="country>
    <option value="US">United States</option>
    .
    .
</select>

<select id="cityselect" name="city"></select>

this is html code and

$.cityselect = function(){
    var td= $('#countryselect').val();
    $.ajax({
        type: "POST",
        url: "action.php",
        data: {'countrytd':td},
        success: function(e){
            $('#cityselect').html(e);
        },
    });
};

this is my chained select function. Mysql process that creating options in action.php.

Here is the thing, when i use this function, the result is that

<select id="cityselect" name="city">
    <option value></option> // empty value
    <option value="1">New York</option>
    <option value="2">Broadway</option>
</select>

i dont want empty value because i need that information. There is no empty value that i wrote to anywhere. There is no problem in php file because when i changed this

$('#cityselect').html(e);

to this

$('#cityselect').html('<option value="1">name</option>');

it adds blank value to top anyway.

how can i disable that process or how can i remove blank value after operation.

Also when i use 'e' that comes from success it includes metatags and some other head elements that i use for language character set in action.php . How can i clean these?


Solution

  • As @roasted stated, it is difficult to fully figure this out without code, but this should resolve at least part of the issue for you:

    First, a note: As of jQuery 1.8 the success callback method is deprecated:

    The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    Here is a solution to some of your problem. It is likely not the solution to all of it, as, if you are getting a blank value from your sql query, there is probably a problem with your query, your database, or both. However, this will provide a 'solution' to the front-end part of your problem -> (This is predicated on the assumption that your php file builds the relevant <option> elements for your <select> element):

    $.cityselect = function(){
    var td= $('#countryselect').val();
    $.ajax({
        type: "POST",
        url: "action.php",
        data: {'countrytd':td},
          }).done(function(data){  
             // better not to use 'e' for this variable (can be confusing)
    
            if($(data).html().replace(/\s/g,'').length){  
            //There are a number of ways to check this 
            //(depends on what you are expecting).
            //  The example I used will also catch blank spaces
    
                   $('#cityselect').html(data);
               }
        })
    };