robert robert - 7 months ago 12
HTML Question

Prevent a selected <option>-tag from being overwritten by .html()

I have a PHP file that fetches rows of car brands from a database, echoes these as

"<option value=\"$brand\">" . $brand . "</option>";
and puts them inside pre-written
<select>
tags.

My issue is that the first item that appears in the select box is not passing its value onwards.

The value of the select box is changed by this event

$('select[name=model]').on('change', function() {
selectedModel = $("#select-model").val()
});


The
<option>
-tags are generated by this loop in
brands.php
:

while ($row = mysqli_fetch_array($result)) {
$brand = $row['brand'];
echo "<option value=\"$brand\">" . $brand . "</option>";
}


The brands are fetched by this function:

function fetchBrands() {
$.ajax({
type: "POST",
url: "script/rent/brands.php",
data: {dateFrom: selectedDateFrom,
dateTo: selectedDateTo,
destination: selectedDestination},

success: function(data) {
$("#select-brand").html(data);
}
});
}


Because the data is posted to
#select-brand
with
.html()
I can't set a default value for the select box because it gets overwritten. Appending the options will result in duplicates etc. as
fetchBrands()
is dependent on a previous set of radio buttons and select boxes.

Answer

What I'd now suggest is that in your success function, add some code that gets the first element in the select tag, updates the selectedBrand, and then triggers the code that's attached to the change event. If you refactored your code so that you added a reference to the handler code, this would make it easier.

$('select[name=model]').on('change', someFunction());

function someFunction(){
    selectedModel = $("#select-model").val()
}

function fetchBrands() {
  $.ajax({
    type: "POST",
    url: "script/rent/brands.php",
    data: {dateFrom: selectedDateFrom, 
           dateTo: selectedDateTo, 
           destination: selectedDestination},

    success: function(data) {
        $("#select-brand").html(data);
        $("#select-brand").val($("#select-brand option:first").val());
        someFunction();
      }
  });
}

Before extra information was added:

To have an element of a <select>...</select> automatically selected on page render, you need to add the attribute selected="selected" to the <option /> you want to be selected.

Alternatively, add a hook for document load that sets the selected brand.

Or, have the first option as something like this:

<option disabled="disabled" selected="selected">Choose a Brand</option>