i´m new developing on asp.net mvc, and even newer using jquery, so this is my problem: i have a few dropdown list that are filled dinamically using the data of another dropdown or textbox, and the data of those drop down is used for another drop down, like a chain, my problem rigth now is that the dropdown sometimes just have one answer/option, and if i try to select that option jquery doesn´t activate the $(“#anything”).change() event, ’cause i have just one option, how i handle it?
http://imageshack.us/photo/my-images/20/sinttulolp.jpg/
for example this i need the data of the red circle for filling the blue circle, but the red circle just have one option and if i click nothing happens
code:
$(document).ready(function() {
$("#tbClave1").autocomplete({
minLength: 1,
source: getClave1,
select: function(event, ui) {
updateClave2(ui.item.value);
}
});
$("#tbClave1").change(function() {
if ($("#tbClave1").val().length == 4) {
updateClave2($("#tbClave1").val());
}
});
$("#ddClave2").change(function() {
updateClave3($("#tbClave1").val(), $("#ddClave2").val());
updateNombre($("#tbClave1").val(), $("#ddClave2").val());
if ($("#ddTipoArticulo").val() == "A" ||
$("#ddTipoArticulo").val() == "B" ||
$("#ddTipoArticulo").val() == "L") {
updatePrecioA($("#tbClave1").val(), $("#ddClave2").val());
} else {
if ($("#ddTipoArticulo").val() == "N" ||
$("#ddTipoArticulo").val() == "H"){
updatePrecioB($("#tbClave1").val());
}
}
});
$("#ddClave3").change(function() {
updateClave4($("#tbClave1").val(), $("#ddClave2").val(), $("#ddClave3").val());
});
});
Edit: example of how i fill one of the dropdownlist
Jquery
function updateClave2(cod) {
var dd = document.getElementById("ddClave2");
dd.options.length = 0;
dd.options[0] = new Option("Espere...");
dd.selectedIndex = 0;
dd.disabled = true;
codigo = cod;
tipoArt = $("#ddTipoArticulo").val();
// Control de errores
$("#ddClave2").ajaxError(function(event, request, settings) {
dd.options[0] = new Option("No se Cargaron Datos");
});
// Obtenemos los datos...
$.ajax({
url: '/Home/GetClave2',
dataType: 'json',
data: { words: codigo, tipoArticulo: tipoArt },
success: function(data, textStatus, jqXHR) {
$.each(data, function(i, item) {
dd.options[i] = new Option(item["clave2"], item["clave2"]);
});
dd.disabled = false;
}
});
}
Controller
public ActionResult GetClave2(string words, string tipoArticulo){
List mySource = miConexion.Clave2(username, password, words, tipoArticulo);
return Json(mySource);
}
As Alex Mendez has wrote, adding a default item to each dropdownlist with text like “Select One” seems to be your easiest answer. You’ll also need to do some handling in case the user re-selects the default “Select One option.” To add default values to your .Net dropdowns try out this code:
or:
EDIT (Missed the MVC)
and in MVC when you bind your initial ViewData just make sure to have your “Select One” in the liest: