Set selected value after ajax call
I have a form where two choices are correlated. After selecting a value from the first, an ajax call is triggered to restore the values of the second. I am using this form to insert and edit data. The first case is smooth. Editing instead does not interact because when I try to set the selected value of the second choice the operation shows nothing. Here's the code:
Html
<select class="inputtext" id="category" name="category" onchange="loadsub(); return false;">
<option value="0"> -- </option>
<?php code to load the values ?>
</select>
<br />
<strong>Subcategory</strong>
<select class="inputtext" id="subcategory" name="subcategory">
<option value="0"> -- </option>
</select>
AJAX
function open(id, edit) {
$('#prod').css("display", "block");
request= 2;
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/prod.php",
data: {
id: id,
richiesta: request
},
async: true,
success : function(data) {
var i = 0;
var tmp = '';
if (data) {
while(i<data.length) {
$('#category option[value="'+data[0]['categoria']+'"]').attr('selected', 'selected');
loadsub();
subcat= data[0]['subcategory'];
if (edit == 1) {
$('#categoria').attr("disabled", true);
$('#sottocategoria').attr("disabled", true);
}
i++;
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//alert("Status: " + textStatus);
//alert("Error: " + errorThrown);
},
complete: function () {
$('#subcategory option[value="' + subcat + '"]').attr('selected', 'selected');
}
});
}
source to share
You should use $.fn.val(value)
to evaluate and move it to the callback completion method
success : function(data) {
//Your code
if(subcat){
$('#subcategory').val(subcat);
}
},
I would recommend that you start using $.fn.prop()
intsead $.fn.attr()
to set properties. Read well .prop () vs .attr ()
To install disabled
use
$('#categoria').prop("disabled", true); //true to disable or false to enable
source to share
don't use select tag to display ajax view using div or other tag. because already selected tag used in ajax page
like your example
<select class="input text" id="category" name="category" on change="load sub(); return false;">
<option value="0"> -- </option>
<? code to load the values ?>
</select>
<strong>Subcategory</strong>
<div class="input text" id="subcategory" >
here is your ajax call
</div>
source to share