Question

Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()).

<select name="Products" id="Products" onchange="getHeadings(this.value);">
  <option value="">Select Product</option>
</select>    

function getProducts(Category) {
  $.ajax({
    type: "GET",
    url: "getInfo.cfm",
    data: "Action=getProducts&Category=" + Category,
    success: function(result){
      $("#Products").html(result);
    }
  });
};

Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user.


Update:

Here's an example of what the script would return

<option value="3">Option 1</option>
<option value="4">Option 2</option>
<option value="6">Option 3</option>

Optionally, if using the .html() method instead of the .append(), I would put another

<option value="">Select a Product</option>

at the top of the result.


@Darryl Hein

Here's an example of what the script would return

<option value="3">Option 1</option>
<option value="4">Option 2</option>
<option value="6">Option 3</option>

Optionally, if using the .html() method instead of the .append(), I would put another

<option value="">Select a Product</option>

at the top of the result.

Was it helpful?

Solution

Can you just change your success function to reset the selected item to the first option?

$("#Products").append(result).selectedIndex = 0;

or to set it to the previous selection?

var tmpIdx = $("#Products").selectedIndex;
$("#Products").append(result).selectedIndex = tmpIdx;

If the onChange event should not fire then you can always set a flag to indicate that the form is updating and change events can check for that flag and exit if it is set.

OTHER TIPS

I just did the following and it worked fine:

<select name="Products" id="Products">
<option value="">Select Product</option>
</select>

<script type="text/javascript">
$('#Products').append('<option value="1">test 1</option><option value="3">test 3</option><option value="3">test 3</option>');
</script>

What is your script returning?

$('#field').find('option:first').attr('selected', 'selected').parent('select');

see this will work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top