This should be a fairly simple task but all the solutions online never worked for me.
I have an array that contains loan types:
var arrLoanType = {
1:"Regular Loan",
2:"Emergency Loan",
3:"Special Loan",
...}
I compare the above to entries in the database, so that the ones existing in the database are removed from the array.
I've looped through them via the code below:
$.each(arrLoanType, function(index, value){
$("#loanType").append("<option value='"+index+"'>"+value+"</option>");
});
Now to the question, what I want to happen is to have a default selected field based on the option's text. This is my code:
$('#loanType option').filter(function () {
return $(this).text() == selectedLoan;
}).attr('selected','selected');
where selectedLoan
is from a hidden input field var selectedLoan = $("#loanSelected").val();
It just doesn't work. This is how my HTML code structure looks like after the $.each
is generated:
<select name="" id="loanType" class="form-control" required="">
<option value="" selected="" disabled="" hidden="">Select Loan Type...</option>
<option value="1">Regular Loan</option>
<option value="2">Emergency Loan</option>
<option value="3">Special Loan</option>
...
I already tried removing "selected" attribute on the first item but it still doesn't work. Any help would be appreciated. Thanks.
you can select the default value on creation itself
$.each(arrLoanType, function(index, value){
if(value == selectedLoan)
$("#loanType").append("<option value='"+index+"' selected>"+value+"</option>");
else
$("#loanType").append("<option value='"+index+"'>"+value+"</option>");
});
the if else checks the text is equal to selected loan or not and add selected attribute in creation itself I think it solves your problem
Seems fine please have a look. Any error in the console? perhaps you forget to include jquery lib or not inside doc ready?
$(document).ready(function(e) { var arrLoanType = { 1:"Regular Loan", 2:"Emergency Loan", 3:"Special Loan"} $.each(arrLoanType, function(index, value){ $("#loanType").append("<option value='"+index+"'>"+value+"</option>"); }); $('#loanType option').filter(function () { return $(this).text() == $("#loanSelected").val(); }).attr('selected','selected'); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <select name="" id="loanType" class="form-control" required=""></select> <input id ="loanSelected" value="Special Loan" type="hidden">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.