Making of an option selected in ajax call not working - javascript

I have tried below lines of code for making an option selected if it matches with the data's DepartmentName. It's not working. Please help !!!
function fillDepartments(selectedText)
{
$.ajax({
url: 'index.php?action=fetchAllDepartments',
type: 'POST',
dataType: 'JSON',
data:{},
success: function(data){
for(var i in data){
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
+ data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +
'</option>');
}
}
});
}

Apply a simple if-else condition:-
for(var i in data){
if(selectedText == data[i]['DepartmentName']){
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '" selected>'+ data[i]['DepartmentName']+'</option>');
}else{
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'+ data[i]['DepartmentName'] +'</option>');
}
}

seems like problem with below code where you are closing tag without including select in it
$('#employee_department').append('<option value="'+data[i]['_id']['$oid']+ '">'
//error as its out of opening bracket
+ data[i]['DepartmentName'] + selectedText == data[i]['DepartmentName'] ? "selected" : "" +'</option>');
you need to include selected in bracket5
<option value='abc' selected></option>
in your case it is
<option value='abc' > selected</option>//wrong

Related

how to take data[index] value in ajax?

Sorry but it's my first time with javascript and ajax
I have this code where i print a list from db in an html select
ajax
'''
$.ajax({
type: 'GET',
url: 'birthplace/list',
dataType: 'json',
success: function(data) {
$.each(data, function(i) {
$('#selectBirthplace').append(
'<option id="' + data[i] + '" value="' + data[i] + '">'
+ data[i].nome + '</option>'
);
});
}
});
'''
html
'''
<div class="item3">
<label for="">Birthplace</label>
<select required class="custom-input" id="selectBirthplace" >
<option value="" selected disabled hidden>Select birthplace</option>
</select>
</div>
'''
Birthplace is a parameter of User but it's still a class.
This is part of a user insert form page.
How can i save the value of data[i] in a variable when the select option was chosen?
i tried with data[i].variable, data[i].class but nothing.

Write Variable javascript in laravel

i am make ajax request on select box to return cities dependent on countries
but when i return old and test if this id of cities contain on array i can't write
the java script variable " key " that refer to city id on this line
i am attached photo of code with question
please help me
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country_id"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: '{!! url('/admin/getCities') !!}/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="ship_to_ids[]"]').empty();
console.log('ok');
$.each(data, function(key, value) {
$('select[name="ship_to_ids[]"]').append('<option value="'+ key +'" {{ (in_array( key , old( "ship_to_ids",
isset($product) ? ($product->ship_to_ids?:[]) : []))) ? "selected" : " " }}>'+ value +'</option>');
});
}
});
}else{
$('select[name="ship_to_ids[]"]').empty();
}
});
});
</script>
Ok the tricky part is here
{{ (in_array( key , ...
in_array is looking for a variable as first parameter and you gave it a constant key so you need to pass your key variable.
Updated
you can do so in your javascript code
var option = '<option value="'+ key +'" {{ (in_array( ":key" , old( "ship_to_ids", isset($product) ? ($product->ship_to_ids?:[]) : []))) ? "selected" : " " }}>'+ value +'</option>';
option = option.replace(':key', key)
$('select[name="ship_to_ids[]"]').append(option);

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?
JSON file
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
I do receive a couple of errors. The Line:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.
Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!
You have a couple of errors in your javascript. See the corrected version below:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
I did a quick fiddle. I don't quite understand what you're doing with v.test being unmarked inside the HTML tags so I did not include it. I used minimal JQuery to avoid complexity.
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
Hope this helps!

how to append a html tag from an ajax call response

I have an ajax function :
$('#app-name').change(function () {//1
console.log("inside change");
var applname= this.value;
console.log(applname);
$.ajax({//2
url: 'foo',
method : 'GET',
dataType : "json",
contentType: "application/json",
data: {"AppID":"appname"},
success: function(data){
var order_data = data;
$('#foo-name').html('');
$.each(order_data, function(i, item) {//3
console.log(order_data[i]);
$('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
});//3
}
});//2
});//1
This function is doing everything else except appending value to the html.
Am i doing it wrong? Can you help solve this issues.
Place the closing </option tag in the jQuery object you create. Don't set it through the html() method. Try this:
$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');
That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this:
success: function(data) {
var options = '';
$.each(data.split(/\n/), function(i, item) {
options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
});
$('#foo-name').html(options);
}
Update You also need to split() the text you state that you're returning before looping through it.
Please use below code in your ajax success event.
success: function(data) {
var _html = '';
$.each(order_data, function(i, item) {
_html += '<option value='+ item +'>'+item+'</options>';
});
$('#foo-name').append(_html);
}

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

Categories

Resources