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

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();
}
});
}

Related

How to prefill fields using jquery

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.

Generate an incremental index in the table

how can I do for this function below to generate an incremental index in the table? Names are being generated right.
I thought of an incremental variable (a), something like that.
function sortear()
{
var a = 1;
$.ajax({
url: 'prize',
type: 'POST',
dataType: 'json',
data: 'employees=' + $('#employees').val() + "&sorted=" + sorteados,
beforeSend: function() {
$('#loading').modal();
},
success: function(data) {
$('#loading').modal('hide');
if (data == null) {
window.alert('Todos os nomes foram sorteados');
$('#button').attr('disabled', 'disabled');
return;
}
$('#employee').html(data.name);
$('#myModal').modal();
$('#sorted tbody').append('<tr><td>' + a + '</td><td>' + data.name + '</td></tr>');
sorteados.push(data.name);
a++;
},
error: function() {
}
});
}
You can get the length of <tr> and sum 1:
/*...*/
// store the element in a variable to reuse it
const $sortedTbody = $('#sorted tbody');
// in the first iteration lenght will be 0, so it will print 1, then 2, etc
$sortedTbody.append('<tr><td>' + ($sortedTbody.children().length + 1) + '</td><td>' + data.name + '</td></tr>');
/*...*/

Display data received from drop box value

I would like once the user selects a different item in the drop box list which was taken from a mysql database, that specific data to that field be displayed.
Currently, I am able to get the value of the item in the drop down box but I am unable to use it.
<h3>Drop down Menu</h3>
<select id="dmenu">
<option selected="selected" id="opt">Choose your station</option>
</select>
<div id="optionT"></div>
$(document).ready(() => {
window.onload = ajaxCallback;
function ajaxCallback(data) {
var data;
var myOptions;
var output;
$.ajax({
url: 'http://localhost:5000/alldata',
type: 'GET',
datatype: 'json',
success: (data) => {
//$.each(data, function (index, value) {
var output = [];
$.each(data, function(key, value) {
output.push('<option value="' + key + '">' + value.Station +
'</option>');
});
$('#dmenu').html(output.join(''));
}
})
}
});
$('#dmenu').on('change', function() {
//alert( this.value );
//alert($(this).find(":selected").value());
function stationData(data) {
var stationName = $(this);
alert(stationName.val());
//var stationName = $(this).value();
//var stationName = $(this).find(":selected").value()
$.ajax({
url: 'http://localhost:5000/alldata',
method: 'POST',
data: {
station: stationName
},
success: (data) => {
$.each(data, function(i) {
data[i]
//console.log(i);
var station_loopOp = '';
//console.log(JSON.stringify(data[i].Station));
station_loopOp += '<li>ID: ' + JSON.stringify(data[i].ID) +
'</li>' +
'<li>Station: ' + JSON.stringify(data[i].Station) +
'</li>' + '<li>Address:
'+JSON.stringify(data[i].Address) +
'</li>' + '<li>' +
Sales: JSON.stringify(data[i].Monthly_CStore_Sales) +
'</li>' + '<li>Operator: ' +
JSON.stringify(data[i].Operator) + '</li>' +
'<li>Top SKU: ' + JSON.stringify(data[i].Top_SKU) +
'</li>' +
'</<li>' + '<br/>');
$('#optionT').html(station_loopOp);
}
});
}
});
You are just defining the function stationData(data){....} inside the callback function but not calling it anywhere inside of it .
Add this line into your function : stationData(<your-data>);

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>');
});
}
});
});

JQUERY fails to set parameter when currentRow.next().next() is not available

I have a jquery save function like this -
$(".SaveBtn").click(function () {
if ($("#Form1").valid()) {
var rowData = $("#TestTable").getRowData($(this).data("rowid"));
var currentRow = $(this).closest("tr");
var postData = {
testID: rowData.testID,
testNotes: currentRow.next().find(".NotesEntry").val(),
isActive: currentRow.next().next().find(".CheckEntry") == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
$.ajax({
type: "POST",
url: "../Services/test.asmx/UpdateTestRowData",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
$("#TestTable").setGridParam({ postData: { myID: $('#hfmyID').val() }, datatype: 'json' }).trigger("reloadGrid");
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
});
The problem is with this line -
isActive: currentRow.next().next() == null ? "false" : currentRow.next().next().find(".CheckEntry").prop("checked"),
};
When currentRow.next().next() is not available, the isActive is not set as "false" and is even not in the request body to web service.
Currently the request body is {"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST"}
I expect it to be -
{"testID":"e9c966ace446-4f73-9ba0-26e686b2a308","testNotes":"TEST", "isActive":"false"}
Why the "isActive" parameter is missed and how to make it available when currentRow.next().next() is not available?
Thanks
I fixed the problem by adding the else part in the following statement -
if (data.d.IsActived) {
output += "<td colspan='6' align=\"left\"><input type='checkbox' id='cbActive" + rowId + " checked" + " name='cbManualDeactive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
else {
output += "<td style=\"display:none;\"><input type='checkbox' id='cbActive" + rowId + " name='cbActive" + rowId + "' class='CheckEntry CheckEntry' data-registrationid='" + data.d.ID + "' data-rowid='" + rowId + "'/></td>";
}
Thanks

Categories