Reputation: 4141
I tried to set a value as "selected" in my edit-form using jquery. Here's my HTML:
var leaveTypeId = $(this).closest('tr').attr('data-leaveTypeId');
$('#leave_type_edit option[value = leaveTypeId]').attr('selected', 'selected');
<div class="col-sm-8">
<select name="leave_type" class="select2-container form-control" id="leave_type_edit">
<option></option>
<?php foreach ($LeaveTypes as $LeaveTypeNew):?>
<option value="<?php echo $LeaveTypeNew->id; ?>"><?php echo $LeaveTypeNew->title; ?></option>
<?php endforeach; ?>
</select>
</div>
The select element is initialized with select2 plugin, if that matters. Any help is appreciated. Thanks.
Upvotes: 2
Views: 134
Reputation: 4153
It wont work because you are not putting it as variable what you actually putted is the string leaveTypeId
not it's value
Change
var leaveTypeId = $(this).closest('tr').attr('data-leaveTypeId');
$('#leave_type_edit option[value = leaveTypeId]').attr('selected', 'selected');
to
var leaveTypeId = $(this).closest('tr').attr('data-leaveTypeId');
$('#leave_type_edit option[value='+leaveTypeId+']').attr('selected', 'selected');
Hope this helps you
Upvotes: 2
Reputation: 16575
Try this one:
$('#leave_type_edit').change(function(){
var leaveTypeId = $(this).closest('tr').attr('data-leaveTypeId');
if($(this).val == leaveTypeId){
$(this).find('option').attr('selected','selected');
}
});
Or:
$('#leave_type_edit').change(function(){
var leaveTypeId = $(this).closest('tr').attr('data-leaveTypeId');
$(this).find('option[value="'+leaveTypeId+'"]').attr('selected','selected');
});
Without change
but onload
:
var leaveTypeId = 2; // for example
$('#leave_type_edit').find('option[value="'+leaveTypeId+'"]').attr('selected','selected');
Upvotes: 1
Reputation: 1681
you can use :
$('#leave_type_edit').val(leaveTypeId );
it play same as example :
$('#get-id').on('click', function () {
let value_select = $(this).attr('data-leaveTypeId');
$('#leave_type_edit').val(value_select);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-sm-8">
<select name="leave_type" class="select2-container form-control" id="leave_type_edit">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<button id="get-id" data-leaveTypeId="2">id check</button>
Upvotes: 2