I have a dropdown that has 3 fields. The value of 2 means that the code box #canaddcodes
should be shown. I have a script like this
$(document).ready(function () {
$('#canaddcodes').hide();
$("#CodeSetup").change(function () {
if ($(this).val() == 2) {
$('#canaddcodes').show();
} else {
$('#canaddcodes').hide(); /* If you want to be hidden if it's not */
}
});
})
I know that the hide value hides that #canaddcodes
but how can i show it on load if the val == 2? I still want to show / hide on change.
答案 0 :(得分:3)
Call the change
event on load:
$(document).ready(function () {
$("#CodeSetup").on("change", function () {
if ($(this).val() == 2) {
$('#canaddcodes').show();
} else {
$('#canaddcodes').hide(); /* If you want to be hidden if it's not */
}
}).trigger("change");
})
Better than put the whole if
statement again outside.
答案 1 :(得分:1)
Chain .change()
to your change handler to invoke it on load:
$("#CodeSetup").change(function () {
if ($(this).val() == 2) {
$('#canaddcodes').show();
} else {
$('#canaddcodes').hide(); /* If you want to be hidden if it's not */
}
}).change(); //<----