I have a div which contains five input fields. Initially the input fields have no value and will be hidden. On dropdown value change I want to update the value of input fields.
For first picture, I have five course code in Semester 1, so all input fields have values. But for second picture I have two course code in Semester 11 so only first two input fields value is changed but the rest of the input fields have previous values. I want to show empty string on those fields. In my jQuery I tried remove and empty functions but it removes my input fields of the div and doesn't show any values.
jQuery
$(document).ready(function () {
var courses = $('#viewCourseCodeField');
courses.hide();
$("#SemesterList").change(function () {
//courses.empty();
var semesterName = $("#SemesterList option:selected").text();
$.getJSON('/Student/GetCourseOfSemester', {semester: semesterName}, function (response) {
$.each(response, function (key, value) {
if (value == null) {
courses.empty();
}
else {
for(var i = 0; i < response.length; i++)
{
var inputField = "c0".concat((i+1).toString());
$('#'+inputField).val(response[i]["courseCode"]);
}
courses.show();
}
});
})
});
});
How can I clear my input fields and fill with only the updated value on dropdown value change?
Your past values from previously selected semester shows. Give the class "cinput" only to the parent div of the inputs, instead of giving the same class to all input fields. To clear all input fields, you can try to set their values to empty before the ajax call;
$(document).ready(function () {
var courses = $('#viewCourseCodeField');
courses.hide();
$("#SemesterList").change(function () {
//courses.empty();
$('.cinput input[type="text"]').val(''); // Add this
var semesterName = $("#SemesterList option:selected").text();
$.getJSON('/Student/GetCourseOfSemester', {semester: semesterName}, function (response) {
$.each(response, function (key, value) {
if (value == null) {
courses.empty();
}
else {
for(var i = 0; i < response.length; i++)
{
var inputField = "c0".concat((i+1).toString());
$('#'+inputField).val(response[i]["courseCode"]);
}
courses.show();
}
});
})
});
});