Reputation: 541
I am using core PHP, jQuery and MySql. I have 2 dependent dropdowns in my code. The first dropdown of company list
is coming from the database directly with a query on the same page.
For the second dropdown of employee list
of particular company
, I am using ajax to get data from database.
var lastSelectedEmpId = $('#hiddeniid').val();
$.ajax({
method: "GET",
dataType: 'json',
url:"getdata.php?id="+emp_id,
success:function (response){
$(".bodytable").empty();
$.each(response, function( index, value ) {
$(".class").append("<option value="'+value.id+','+value.emp_type+'">" + value.emp_name + </option>'");
});
},
});
As you can see above code in value "'+value.id+','+value.emp_type+'"
On _GET['curent_id']
I am getting selected users all data.
My add and update code is on same page. So I have only single ajax call for employee_list.
As you see above code on _GET['curent_id']
, I am getting all data with id_emptype
of employee.
I want this id_emptype
to use in ajax call as selected option. For this, I want to use a ternary operator inside jQuery, but it's not working
for me.
I have one hidden field with my current id_emptype
. in variable lastSelectedEmpId
.
Now I'm doing something like below code to get current id_emptype
as selected value onload page, but its not working:
$(".class").append<option value="' +value.id+','+value.emp_type+ '"' +
(+value.id+','+value.emp_type+ === lastSelectedEmpId ? 'selected="selected"' : '') +
'>' + value.emp_name + '</option>;
Upvotes: 0
Views: 1539
Reputation: 33943
When concatenating some JS logic with a string, you have to wrap it with parenthesis.
And be careful where you put the +
signs and the parenthesis. You just can't have them at the wrong place or missing.
Try the .append()
below, where I filled the variables with stuff to have the demo working:
var lastSelectedEmpId = "1,type";
var value={
id:1,
emp_type:"type",
emp_name:"John Doh"
}
$(".class").append('<option value="' +value.id+','+value.emp_type+ '"' +
((value.id+','+value.emp_type === lastSelectedEmpId) ? 'selected="selected"' : '') +
'>' + value.emp_name + '</option>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="class">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
===
And 'selected="selected"'
could simply be 'selected'
. That attribute is a true/false anyway. But browsers interpret it to be true simply if present.
You can even try 'selected="bullshit"'
and it will work... ;)
Upvotes: 1