How to prefill fields using jquery - javascript

Hi I'm trying to figure out how to fill all fields using ajax call, it successfully doing by selecting category, it loads all related sub_categories.
But sub_sub_category fields are empty. Only when I choose sub_category option it will load all sub_sub_categories, but I want all prefilled once category has been changed. I don't mind to leave like this, but problem is if I have only single sub_category I can not select any sub_sub_category even if they have any I tried to convert to function and call them but no success.
Code below:
<script>
$(document).ready(function() {
get_sub_sub_category();
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if(category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/"+category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="'+ value.id +'">' + value.sub_category_name + '</option>');
});
get_sub_sub_category();
},
})
} else {
alert('danger');
}
});
function get_sub_sub_category() {
$('select[name="sub_category_id"]').on('load change', function () {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/"+sub_category_id,
type: "GET",
dataType: "json",
success: function (data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function (key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
}
});
</script>

You might want to consider the following.
$(function() {
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if (category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/" + category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_category_name + '</option>');
});
$('select[name="sub_category_id"]').trigger("change");
},
})
} else {
alert('danger');
}
});
$('select[name="sub_category_id"]').on('change', function() {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/" + sub_category_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
});
This defined the callbacks for both. For category, when it is changed, it triggers change event on sub-category. This in turn will cascade the loading of the next Select.

Related

How to pass return value in Javascript to the Controller

This is my Javascript code that gets the value from the query string
function getUrlVars() {
var name = [], hash;
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
hash = url[i].split('=');
name.push(hash[0]);
name[hash[0]] = hash[1];
var hid =hash[1];
return pid;
}
}
var hid = getUrlVars()['pid'];
This is my URL: http://localhost:33454/Product?pid=1
[HttpGet]
[Route("api/product/getproducts/{pid}")]
public IActionResult Product(int pid)
{
var selectProducts= (from p in _db.Products
where p.ProductId == pid
select p).ToList();
return Ok(selectProducts);
}
This is my AJAX for printing the list to the html
var $view = $('.table')
$(function () {
$.ajax({
type: 'GET',
url: '/api/product/getproducts/{pid}',
datatype: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});
Are there any issues with my code. Sorry, I know this might be a really simple question to you all. I'm new to programming.
Thanks in advance.
The API URL is not being constructed properly for the AJAX call.
//...code omitted for brevity
var hid = getUrlVars()['pid'];
//...
var $view = $('.table');
$(function () {
$.ajax({
type: 'GET',
url: '/api/product/getproducts/' + hid, //<<<<
datatype: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});
Change your code to this.
[HttpPost]
public IActionResult Product(int pid)
{
var selectProducts= (from p in _db.Products
where p.ProductId == pid
select p).ToList();
return Json(selectProducts, JsonRequestBehavior.AllowGet);
}
And this should be:
Replace {ControllerName} with your controller's name with no curly braces
For example: url: '/Clients/Details'
var $view = $('.table')
$(function () {
$.ajax({
type: 'POST',
url: '/{ControllerName}/Product',
data: JSON.stringify({ pid: hid}),
dataType: 'json',
success: function (products) {
$.each(products, function (i, product) {
$view.append('<td class="products">' + product.productName + '</td>', '<td class="products">' + product.productDescription + '</td>');
});
}
});
});

set item title ​from sharepoin list in an asp: RadioButtonList

This is my first question on Stack Overflow.
I am developing a solution in SharePoint online and I have a list that has several items, I need to get the titles of those items and insert them in a RadioButtonList, so that, when a new item is added, the radio button can take the new item. Thanks!
Try to do it the way DropDownList, but it does not work...
function loadDdl(ddlId, list) {
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
$.ajax({
url: siteUrl + "/_api/web/lists/GetByTitle('" + list + "')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
$.each(data.d.results, function (key, value) {
$("#" + ddlId).append($("<option></option>")
.val(value.Title)
.html(value.Title));
});
sortDropDownListByText();
},
error: function (error) {
alert(JSON.stringify(error));
loadingOff();
}
});
}
Inserting items into the DDL:
$(document).ready(function () {
// SP.SOD.executeFunc('sp.js', 'SP.ClientContext', initializePage());
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', revisarPermisos);
var emitidoPor = _spPageContextInfo.userDisplayName;
$("#lblEmitidoPor").append(emitidoPor);
loadDdl("ctl00_PlaceHolderMain_ddlEmisor", "Departamentos");
loadDdl("ctl00_PlaceHolderMain_ddlDepartamentoDeHallazgo", "Departamentos");
loadDdl("ctl00_PlaceHolderMain_accionesRdl", "Departamentos");
$("#hlNuevaSolicitud").addClass("active");
loadingOff();
});
This is the solution, and how to insert list item in a RadioButtonList
function loadRbl(RblId, lista) {
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
$.ajax({
url: siteUrl + "/_api/web/lists/GetByTitle('" + lista + "')/items",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
var i = 1;
$.each(data.d.results, function (key, value) {
$("#" + RblId).append($("<tr><td>"
+ "<input type='radio' id='" + RblId + i+ "'
name='ctl00$PlaceHolderMain$rdlAccion' value='" + value.Title
+ "'>"
+ "<label for='" + RblId + i+"'>" + value.Title + "</label>"
+ "</td></tr>"));
i++;
});
},
error: function (error) {
alert(JSON.stringify(error));
loadingOff();
}
});
}

How do I get all values of checkbox those are checked using ajax/jQuery in asp.net

When i click the Select working days / hours Checkbox the list of days will be displayed. for example if i click the sunday checkbox check box the value entered in the checkbox should be call to javascript function. in case am not click the checkbox the value display should be Null.
DEMO LINK HTML
$(document).ready(function () {
$("input#btnDocBusinesshours").click(function () { SaveDocBusinesshours(null) });
});
Call Ajax Function
function callAjax(jparms) {
$.ajax({
type: "POST",
url: jparms.url,
data: jparms.data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (jparms.action == "SaveDocBusinesshours")
SaveDocBusinesshours(response.d)
},
failure: function (response) { response.d; }
});
}
Save Ajax Function
function SaveDocBusinesshours(response) {
var values = $('input[type="checkbox"].single:checked').map(function () {
return $(this).val();
}).toArray();
if (response == null) {
callAjax({
url: pageUrl + '/SaveDocBusinesshours',
data: '{"Doctorid": "' + $("#<%=hdnDoctorId.ClientID %>").val() + '","WorkingDaysID" : "' + $("#<%=hdnBusiness.ClientID %>").val() + '","Sunday" : "' + $("#<%=ChkSUN.ClientID %>").val() + '","Monday" : "' + $("#<%=ChkMON.ClientID %>").val() + '","Thuesday" : "' + $("#<%=ChkTUE.ClientID %>").val() + '"}',
action: "SaveDocBusinesshours"
});
window.location.reload();
}
else {
loading(false);
if (response.AjxContactId != null) {
$('#<%=hdnBusiness.ClientID%>').val(response.AjxContactId);
}
msg(true, response.Message);
}
}
Webmethod:
[WebMethod]
public static UserAjax SaveDocBusinesshours(string Doctorid, string WorkingDaysID, string Sunday, string Monday, string Thuesday)
{
UserAjax oUserAjax = new UserAjax();
return oUserAjax;
}

Nested ajax call with an value from the first into the seconds Ajax call's url

I want to do live search and I need to use an id value from the first ajax call inside the second one.
I get the info when I type fast into the search, but if I search again or continue, I get this and the outer ajax wont be called again.
GET
http://api.themoviedb.org/3/movie/366924/videos?api_key=KEYHERE…9a6ebe&callback=jQuery1102017797202615180896_1472038138300&_=1472038138301
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val(),
movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
}
})
.then(function() {
$.each(resultArray,
function (index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function () {
$("#myList").append("stuffs");
}
});
});
});
}
$(this).change();
});
Try This -
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val();
var movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
$.each(resultArray,
function(index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function() {
$("#myList").append("stuffs");
}
});
});
}
});
}
$(this).change();
});

Jquery not working while process dynamically

The below code works for me
function gethotelsbydestination(dest_id) {
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
$("#divid").html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
$("#divid").append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
But when i use below code not returns anything.divv is the id of an dropdown passed from php page
function gethotelsbydestination(dest_id, divv) {
var divdrp = "$('#" + divv + "')";
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
divdrp.html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
divdrp.append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
The problem is var divdrp="$('#"+divv+"')";
Any Solution please
You can't concatenate directly. Use this:
divdrp = $('#' + divv);
instead of this:
var divdrp = "$('#" + divv + "')"; // it is not a jquery object

Categories