I'm kinda new to javascript and ajax.
The page that I'm building will ask user to select from a list. Upon selection, a dropdown will be populated from database, and a default value of that dropdown will be automatically selected.
So far I've been able to populate the dropdown OR automatically select a value. But I can't do them both in succession.
Here's the Javascript snippet that gets called upon selection of an item from a a list:
function onSelectProduct(data, index) {
//part 1: auto populate dropdown
$.ajax({
type: "POST",
async: true,
url: "http://localhost:8007/Webservice.asmx/GetUnitsByProductID",
data: "{productID: " + data.ID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$("#Details_" + index + "_ConversionID").empty();
$.each(result.d, function (key, val) {
var option = document.createElement('option');
option.text = val.Name;
option.value = val.ID;
$("#Details_" + index + "_ConversionID").append(option);
});
}
});
//part 2: select one of the values
var ddl = document.getElementById("Details_" + index + "_ConversionID");
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == data.StockUnitID){
ddl.options[i].selected = true;
break;
}
}
}
I used
$("#Details_" + index + "_ConversionID").empty(); because I started with all possible options in the dropdown.
If I started with an empty dropdown, ddl.options.length will return 0 for some reason.
From my understanding, the ajax script that I wrote doesn't really change the properties of the dropdown box (ddl.options.length returns either 0 or the full list with or without the ajax operation). If that's true, then what's the right way to populate that dropdown?
Btw I'm using cshtml and .net.
Thanks!
Well you can try using $.when and .done as below:
It will execute your code once the options have been set
$.ajax({
type: "POST",
async: true,
url: "http://localhost:8007/Webservice.asmx/GetUnitsByProductID",
data: "{productID: " + data.ID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$("#Details_" + index + "_ConversionID").empty();
$.when(
$.each(result.d, function (key, val) {
var option = document.createElement('option');
option.text = val.Name;
option.value = val.ID;
$("#Details_" + index + "_ConversionID").append(option);
})).done(function(){
//part 2: select one of the values
var ddl = document.getElementById("Details_" + index +"_ConversionID");
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == data.StockUnitID){
ddl.options[i].selected = true;
break;
}
}
});
}
});
I would also like to suggest one thing! Please do not use complete url as your ajax url since when you host the site this will change and http://localhost:8007/ will no longer be available!
You can write following code in Ajax Success :
$("#Details_"+index +"_ConversionID").val('value you want to select');
Thanks
Related
Click event on task list, when edit button clicked modal box appears and populate data from ajax call.
First time I click edit button it show first option, but when 2nd click it show the corrected one even when I click on other row. Staff show just right, the problem is on phase.
This is my final solution:
$('#task_table').on('click', '.edit_task', function() {
var task_id = $(this).attr('data');
$('#modal-task-edit').modal('show');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() . 'Task/get_task' ?>',
data: {
task_id: task_id
},
async: false,
dataType: 'json',
success: function(data) {
$('input[name=start_date]').val(data.start_date);
$('input[name=project_id]').val(data.project_id);
$('input[name=task_id]').val(data.task_id);
$('input[name=end_date]').val(data.end_date);
$('input[name=task_name]').val(data.task_name);
$("textarea#task_description").val(data.task_description);
let phases = data.phases.split(",");
all_phase(result => {
let arr_all = [];
let all = Object.keys(result).map((key) => [result[key]]);
for (let i of all) {
arr_all[i[0]['phase_id']] = i[0]['phase_name']
}
for (let i = 0; i < phases.length; i++) {
$('#phase').append('<option value=' + phases[i] + '>' + arr_all[phases[i]] + '</option>');
}
});
$('#phase').val(data.phase_id).trigger('change');
$('#pic').val(data.staff_id).trigger('change');
}
});
});
Hours of debugging doesn't work
I have implemented autocomplete feature using JQuery, but now I wanted to store last 20 searched per inputfield in browser. So, if user when focuses the suggestion will be fetched from the browser. If user types then from Rest API using ajax I am fetching the data.
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'page':1,'size':"10"};
params[id]=request.term;
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url:"http://localhost:5645/search",
data: jsonParams,
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//const result = new Set()
var result=[];
console.log(id);
console.log(msg.details)
console.log(msg.details.length)
for(var i = 0; i < msg.details.length; i++) {
var obj = msg.details[i];
if(obj!=null && columnMapping[id]!=undefined && obj[columnMapping[id]]!=undefined){
console.log(obj[columnMapping[id]]);
//result.add(obj[columnMapping[id]]);
result.push(obj[columnMapping[id]]);
}
console.log(result);
}
//response(Array.from(result));
response(result);
}
/* error: function() {
response([]);
} */
})
},
select: function(event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log('test');
var item = $("<div>" + item.label + "</div>")
return $("<li>").append(item).appendTo(ul);
};
Above is the jquery code which I am using for autocomplete. So, if no input is there I need to fetch from browser recent search. So, when user types unique search keys should be inserted. How I can store and retrive using javascript.
I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
function FillBooks(val) {
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$("#DDL_TIPO").empty();
$.ajax({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: "POST",
dataType: "JSON",
data: { value: CategoryId },
success: function (data) {
var markup = "<option value='0'>Selecione um Tipo</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
}
$("#DDL_TIPO").html(markup).show();
}
});
}
P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.
Try this:
<script>
function FillBooks(val)
{
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$.ajax
({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: { value: CategoryId },
success: function(result)
{
$("#DDL_TIPO").html("");
$.each($.parseJSON(result), function(i, tipo)
{
$("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
})
},
error: function()
{
alert("Whooaaa! Something went wrong..")
},
});
}
</script>
I want to display the value based on selected value on drop down list with using Get method of Ajax from the url,
based on schema i have to add the value of selected item to the meddle of url and then i can get the relative data from the server:
this is my code:
$.ajax({
type: 'GET',
url: 'url',
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#tbl2").append("<option>"+data[i]+"</option>");
}
}
});
var one = 'http://gate.atlascon.cz:9999/rest/a/';
var middle = $('#tbl2 :selected').text(); // it should be the selected item from last get method
var end = '/namespace';
var url_t = one + middle + end ;
$.ajax({
type: 'GET',
url: url_t,
success: function(data2) {
$("#text-area").append(data2);
}
but it is not work!
i am new in programming, could you please help me.
thanks.
try this:
$.ajax({
type: 'GET',
url: 'url',
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#tbl").append("<tr><td>"+data[i]+"</td></tr>");
}
}
});
Add this in your ajax success():
data.forEach(function(item) {
$("#tbl").find('tbody')
.append($('<tr>')
.append($('<td>').text(item))
);
})
Basically just need to write a jQuery/Ajax that fetches Json data (Price data) from server
and appends/overwrites each options text value so it would have the price difference between the
selected option and non selected option on the end of it. Only the non selected option should have the price difference showing on the end of it, see example below.
The code you will find below pretty much does this, but I can't seem to properly append/overwrite
it to the end of the option text value without the price difference being repeated (not replaced) onto the end with every onchange of the dropdown list. So I get [product name025252525] etc.
As well no idea how to not append the difference to the selected options text, I just get "0" there now as it minuses itself from itself.
The Json object (data) array is of the format {partid = 3, price = 234}, {partid = 6, price = 53} etc.
List should look like so:
[Intel i7 950] - selected visible option
[Intel i7 960 (+ $85)] - not selected but in the drop down list
[Intel i7 930 (- $55)] - not selected but in the drop down list
<script type="text/javascript">
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { mydata = data; OnSuccess(data) },
dataType: "json"
});
});
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
break;
}
};
$(this).find('option').each(function () {
// $(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
var newtext = uop - sop;
var xtext = $(this).text().toString();
$(this).attr("text", xtext + newtext);
// mob.append(newtext)
// $(this).next('span').html(newtext);
});
});
};
//$(document).ready(function () { $("#partIdAndCount_0__PartID").prepend('<option value="0">Select Processor<option>'); });
</script>
You are close:
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: OnSuccess,
dataType: "json"
});
OnSuccess is a function taking one parameter, data. So you simply use that method like above.
$('select').change(OnSuccess(data);); would compile if fixed like $('select').change(OnSuccess(data)); , minus the semicolon in the function. However, this is executing OnSuccess immediately. So again, $('select').change(OnSuccess); is what you want.
Declare a variable to store it in the outer scope:
var theJSON;
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { theJSON = data; OnSuccess(theJSON)},
dataType: "json"
});
});
$('select').change(function(){ OnSuccess(theJSON); });