Share Knowledge Share Knowledge - 2 months ago 8
jQuery Question

Clean all selected option after ajax request

Selecting values from drop-down according to the data that retrieved from Ajax request to database by clicking on update link and when i console.log the response i can see data has been retrieved and i am successfully able to compare it with drop-down list and if there is a match one of the option values will be selected.

If i click on clean button to clear the selected option, it works for the first time.

But if i click on the update link again to retrieved data i can see data has been retrieved when i console.log the response but nothing is selected from the drop-down.

Any help - here is my code down below

<p>
<a href="javascript:;" class="updateCenter">Update</a>
</p>

<form method="post" action="controller/update" class="formInuts">
<select required="" name="semester_id" class="form-control semester">
<option value="">Pleas Select</option>
<option value="1">Semester 1</option>
<option value="2">Semester 2</option>
<option value="3">Semester 3</option>
</select>
<button type="submit" class="btn btn-primary saveCorCnt">SAve</button>
<button type="" class="btn btn-primary clearCorCnt">Clean</button>


// Update
$('.updateCenter').on('click', function(event) {
event.preventDefault();

// semester id
var corcnt_id = 1;

$.ajax({
url: url+'/findcorcnt',
type: 'POST',
dataType: 'JSON',
data: {
corcntid: corcnt_id
},
beforeSend: function() {
},
success: function(respond) {
// Data retrieved successfully
// first time and every time i click on update link
// Changing the current action to update
var formInuts = $('.formInuts').attr('action',url+'/updatecorcnt');

// Change save btn to update
var saveBtn = $('.saveCorCnt').text('update');

// Selecting the values from dropdowns semesters
$('.semester option').each(function(){
if (parseInt(this.value) == respond.semester_id) {
$(this).attr('selected', true);
}
});
});

$('.clearCorCnt').on('click', function(event) {
event.preventDefault();

$(':input','.formInuts')
.removeAttr('checked')
.removeAttr('selected')
.not(':button, :submit, :reset, :hidden, :radio, :checkbox')
.val('');

var saveBtn = $('.saveCorCnt').text('save');
});

Answer

No need to compare using loop. Just try like following.

$('.semester').val(respond.semester_id);
Comments