Tuesday, October 20, 2020

How to set value to dropdown list with ajax

How to set the value to the dropdown list after getting options with ajax

HTML

<div class="modal-body">
<form th:action="@{/projects/addNew}" method="post">
<div class="form-group">
<label for="ddlLocationAdd" class="col-form-label">SELECT Location: </label>
<select class="form-control" id="ddlLocationAdd" name="locationId">
<option th:each="location : ${locations}"
th:value="${location.id}"
th:text="${location.name}">
</option>
</select>
</div>
<div class="form-group">
<label for="ddlCompanyAdd" class="col-form-label">SELECT Company: </label>
<select class="form-control" id="ddlCompanyAdd" name="companyId">
</select>
</div>
<div class="form-group">
<label for="projectName" class="col-form-label">Project Name:</label>
<input type="text" class="form-control" id="projectName" name="name">
</div>
<div class="form-group">
<button type="submit" value=" Send" class="btn btn-success" id="submit">Submit</button>
</div>
</form>
</div>

JS

$('select[name="locationId"]').on('change', function() {
var locationId = $(this).val();
console.log(locationId);

$.ajax({
type: "GET",
url: "getCompanyByLocationId?locationId="+locationId,
success: function (data){
console.log(data);
$('#ddlCompanyAdd').html('');
for (var i=0; i< data.length; i++){
var company = data[i];
console.log(company);
console.log(company.name);
var option = $('<option>').val(company.id).text(company.name);
$('#ddlCompanyAdd').append(option);
}
}
});
});
$('#ddlLocationAdd').trigger('change');

No comments:

Post a Comment