Add custom object as option inside dropdownlist - javascript

I'm having some kind of a bad time where i need to append some json objects as selectlistitems inside a dropdownlist that is different from where i display these json objects.
I managed to retrieve all data, but i dont know how to translate all the information from one kind of element to another. Currently i set up something like this:
All objects that come from my JsonResult method in controller comes like this:
Jsonresult
and the current format for my dropdownlist is as follows:
Dropdownlist selection from controller
For right now I have come to the current state:
i created an array that stores all my objects and convert them to tags, but as i went debugging my array looks like this:
Array from ajax as option tags
My Ajax Request is working as follows:
function GetContratosFiltro() {
$("#id_contrato_aplicativo").empty();
$("#ckSelecionarTdsContratosFiltro").removeAttr("disabled");
var array_sistema = $('#id_sistema').val();
var array_build = $('#id_build_verus').val();
$.ajax({
type: "POST",
url: '#Url.Action("GetContratosFiltros")',
dataType: "json",
//data: "{ 'id_sistema': '" + array_sistema + "'," + "'id_build_verus': '" + array_build + "'}",
data: JSON.stringify({ id_sistema: array_sistema || null, id_build_verus: array_build || null }),
contentType: "application/json; charset=utf-8",
success: function (contratos) {
console.log(JSON.stringify(contratos));
var formoption = [];
content = contratos;
$.each(contratos, function (index, element) {
console.log(element);
var xx = $('<div class="checkbox">' +
'<input value="' + element.id_contrato + '" type="checkbox" name="' + element.contrato + '" class="form-check-input" id="' + index + '" checked>' +
'<label class="form-check-label" for="' + index + '">' + element.contrato + '</label>' +
'</div >');
$('#id_contrato_aplicativo').append(xx);
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " < option value = '" + element.id_contrato + "' id='" + element.id_contrato + "' > " + element.contrato + "</option >";
}
});
array = formoption;
$("#ckSelecionarTdsContratosFiltro").prop('checked', true);
console.log('formoption: ' + formoption);
console.log('array: ' + array);
console.log(content);
},
error: function (ex) {
//alert('Failed to retrieve states.' + ex);
}
});
}
My output on the filter modal is, for example:
Modal filter
On this code: id_contrato_aplicativo is a div where i store all the results from jsonresult query and displays them as checkboxes divs with input and labels, by this bootstrap documentation Checkboxes. My HTML consists into a modal with the filter options with two fields that send information to controller and the main dropdown just gets all information from regular query in controller, but i'm using a custom class called select2 which create the layout for my application and generate the multiselect dropdownlist as a element with each new showing as a block inside dropdown selection, like the image below:
Dropdown result
This code is where i generate all tags for each item from ajax call and below is the function that i am testing right now.
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " < option value = '" + element.id_contrato + "' id='" + element.id_contrato + "' > " + element.contrato + "</option >";
}
$('#btnTransf').click(function () {
console.log('clicou no botão!')
for (var i = 0; i < array.length; i++) {
array[i].appendTo('#id_contrato select');
$('#id_contrato').select();
//appends to select if parent div has id dropdown
//return !$("#id_contrato_aplicativo :checked").remove().appendTo('#id_contrato');
}
//return !$("#id_contrato_aplicativo :checked").remove().appendTo('#id_contrato');
});
UPDATE:
i have managed to locate the correct element and turn out that i only need to pass all elements already formated array variable with all elements as tags inside id_contrato element.
Removed useless info

I've managed to get it to work by making an event bind on a button that gets each element of my array of already formatted objects and with its ids as values from tags.
Array Structure example ( from ajax call):
array = []; //external variable
//put this susccess inside your call from ajax, considering a JsonResult as your controller method
success: function (contratos) {
console.log(JSON.stringify(contratos));
var formoption = [];
content = contratos;
$.each(contratos, function (index, element) {
console.log(element);
var xx = $('<div class="checkbox">' +
'<input value="' + element.id_contrato + '" type="checkbox" name="' + element.contrato + '" class="form-check-input" id="' + index + '" checked>' +
'<label class="form-check-label" for="' + index + '">' + element.contrato + '</label>' +
'</div >');
$('#id_contrato_aplicativo').append(xx);
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " <option value='" + element.id_contrato + "'selected> " + element.contrato + "</option>";
}
});
array = formoption;
$("#ckSelecionarTdsContratosFiltro").prop('checked', true);
console.log('formoption: ' + formoption);
console.log('array: ' + array);
console.log(content);
}
Code:
$('#btnTransf').click(function () {
console.log('test to check if click successful!')
$.each(array, function (index, element) {
console.log(element);
$('#id_contrato').append(element);
$('#id_contrato').select();
});
});

Related

How to restrict the selection of one Radio Button in C#?

This is my code to select one item at a time.
But both the options are getting selected. How can I solve this issue?
function initializehrm__documentidRadiobuttonlist(documentid) {
debugger
ajaxCall("/Client/SysType/GetSysTypeByTypeGroupCodeAndSyslevel", { "typeGroupCode": sysTypeGroupCodeEmployeeImmigrationDocument }, "POST", "callback_initializehrm__documentidRadiobuttonlist", documentid);
}
function callback_initializehrm__documentidRadiobuttonlist(data, documentid) {debugger
data = data.data;
var hrm__documentidRadiobuttonlisthtml = "";
$.each(data, function (index, item) {
item = removeVirtualObjectPropertiesFromJsonObject(item);
hrm__documentidRadiobuttonlisthtml += "<div><input type='radio' id='documentid" + index + "' value=" + item.id + " /><span>" + item.title + "</span></div>"
});
$("#rdohrm__documentid").html(hrm__documentidRadiobuttonlisthtml);
}
Multiple radio buttons must share the same name (the value of the name attribute), so that it is treated as a group, and only one selection is allowed.
Modify your < input > tag something like below:
"<div><input type='radio' id='documentid" + index + "' value=" + item.id + " name='documents' /><span>" + item.title + "</span></div>"

How to apply style sheet on dynamic generate radio button?

here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');

Wait for button click event before continue loop Javascript

I have a code loop that adds options to a popup modal, with buttons alongside each option.
In a search loop, sometimes when the search returns multiple items, we must show the modal, and the user selects which part.
I want to pause the loop and wait for the user to choose an item, before continuing.
MY LOOP
$.each(rows, function (index, item) {
SearchItems(item.split('\t')[0], item.split('\t')[1]);
});
SEARCH ITEM FUNCTION
function SearchItems(searchedPart, quantity) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "OrderFormServices.asmx/GetItemInfoAdmin",
data: "{'itemname':'" + searchedPart + "','quantity':'" + (quantity || 1) + "', 'guid':'" + custGuid + "' }",
dataType: "json",
success: function (result) {
result = result.d;
if (result.length > 1) {
var htmlString = "";
$.each(result, function(index, item) {
item.PartNumber = (item.PartNumber != "") ? item.PartNumber : item.ItemName;
htmlString += "<tr><td>"
+ "<input type=\"hidden\" name=\"ItemID\" value=\"" + item.ItemID + "\">"
+ "<input type=\"hidden\" name=\"ItemCode\" value=\"" + item.ItemCode + "\">"
+ "<input type=\"hidden\" name=\"Price\" value=\"" + item.Price + "\">"
+ "<input type=\"hidden\" name=\"Quantity\" value=\"" + item.Quantity + "\">"
+ "<input type=\"hidden\" name=\"CustomerReference\" value=\"" + searchedPart + "\">"
+ "<input type=\"hidden\" name=\"PackQuantity\" value=\"" + item.PackQuantity + "\">"
+ "<input type=\"hidden\" name=\"FreeStock\" value=\"" + item.FreeStock + "\">"
+ item.PartNumber + "</td><td>"
+ item.ManufacturerName + "</td><td>"
+ item.ItemName + "</td><td>"
+ item.ItemDescription + "</td><td><input type='button' name=\"selectPopup\" onclick=\"ChoosePopup($(this).closest('tr'));\" class='btn btn-primary btn-xs' value='Select'></td></tr>";
});
$("#tbodyPopupContent").html(htmlString);
$("#PopUpNormalProduct").modal();
modalfix();
$("#divPopupWindow").parent("").addClass("quicksearchpopup");
//////////////////////////////////////////////////////////////////////////
//////////////// WAIT FOR BUTTON CLICK AND PERFORM CODE///////////////////
//////////////////////////////////////////////////////////////////////////
$("#partNumber").prop("disabled", false);
} else if (result.length < 1) {
$("#partNumber").prop("disabled", false);
$('#partNumber').focus();
}
else {
///////
}
}
});
}
The popup item buttons fire a ChoosePopup() function.
function ChoosePopup(row) {
var $hidden_fields = row.find("input:hidden");
var $tds = row.find("td");
var newItem = {
ItemID: parseFloat($hidden_fields.eq(0).val()),
ItemCode: $hidden_fields.eq(1).val(),
ItemDescription: $tds.eq(3).text(),
ItemName: $tds.eq(2).text(),
Price: parseFloat($hidden_fields.eq(2).val()),
Quantity: parseFloat($hidden_fields.eq(3).val()),
CustomerReference: $hidden_fields.eq(4).val(),
PackQuantity: parseFloat($hidden_fields.eq(5).val()),
FreeStock: parseFloat($hidden_fields.eq(6).val())
};
AddNewRow(newItem, true);
$("#PopUpNormalProduct").modal("hide");
}
How can I wait for this ChoosePopup() function to complete, before continuing the loop?
I think you should re-think the way you are approaching the problem. You should fire your ChoosePopup function with a callback to do the rest of the work based on the user input.
You might consider passing the rows array into the SearchItems function, so that you can setup your callback to iterate through the remaining items in rows.
Here's an example that doesn't require duplicated code.
const items = [1, 2, 3, 4, 5]
//main function which writes buttons from an array
function makeButtons(array) {
//copy the array so we can keep track of which items are left to process after click event
var unProcItems = array.slice()
$.each(array, function(index, item) {
var exit = false
//remove the item from the processed array
unProcItems.splice(unProcItems.indexOf(item), 1)
//make our button
var button = document.createElement('button')
button.innerHTML = `Button ${item}`
//if something then hook up a click event with callback
if (item == 3) {
button.onclick = function(event) {
//call our makeButtons function in the callback passing in the unprocessed items array
makeButtons(unProcItems)
//remove the click event so it can't be fired again
event.target.onclick = null
}
exit = true
}
document.getElementById('content').append(button)
//exit the loop if our flag was set
if (exit)
return false;
})
}
makeButtons(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>
Define global variables and based on what the pop up asks for, move the rest of your code to ChoosePopup() Function.

incorporating pagination in ajax json

I have a ajax json retrieving all query results in a div.I'm not sure how to introduce pagination though.
<script>
$(document).ready(function () {
var hdnIds = document.getElementById('<%= HiddenField1.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebService1.asmx/GetEmployees",
data: "{userid: " + JSON.stringify(hdnIds) + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (list) {
$("#Something").append("<ul id='bullets' class='ul1'></ul>");
for (i = 0; i < list.d.length; i++) {
$("#bullets").append("<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
},
error: function (e) {
$("#Something").html("There was an error retrieving records");
}
});
});
</script>
And html as
<div id="Something"></div>
ANy help will be greatly appreciated!
First, I would read up on javascript templating. There are a lot of libraries out there that will allow you to remove the bloated html code from your JS code so that it's easier to manage. Something like this: https://github.com/BorisMoore/jquery-tmpl.
After that, you should put the responsibility of pagination on the server side and let the JS/Ajax handle the calls to retrieve the data set. For instance:
//server side
var start = request.params.start //retrieve start index for data set
var limit = request.params.limit //retrieve max number of data set size
return db.Model.find({start: start, limit: limit, ...})
//client side JS/Ajax
//load first page 0-9
$.ajax({
url: '/my/data/url',
params: {
start: 0, //start at first record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
//load second page 10-19
$.ajax({
url: '/my/data/url',
params: {
start: 10, //start at nth record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
If I understand the question correctly, you already know about append which is what you need, but you need to change all your ids to classes since there will be more than 1 of them. Then, put all of the html you want to append into a string and just append that html.
HTML:
<div id = "parent">
<div class = "Something"></div>
</div>
JAVASCRIPT (replace to the success AJAX call):
var htmlList = "<div class = "Something"><ul class='bullets ul1'>";
for (i = 0; i < list.d.length; i++) {
htmlList += "<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
htmlList += "</ul></div>";
$("#parent").append(htmlList);

Creating dynamic html with json taking too much time

I am working on preparing some dynamic html with jquery and json object. but the problem is that when my json object has around 1500 rows it takes ages to load.
is there a way to load the thing faster.
Some code.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
innerList1 += '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>';
}
else if (type = "exportall") {
innerList2 += CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat);
}
controlId++;
}));
$("#itemList").html(innerlist1);
EDIT : createliwithspan method
function CreateLiWithSpans(id, html, isLeft, isAddAll, scaleID, scaleType, hasWeights, customColumnType, valueFormat, newText) {
var ancClass = isLeft ? 'actionRight' : 'actionLeft';
var liObject = "";
if (newText == null) {
newText = "";
}
if (isLeft) {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><span style="margin:0 10px 0 20px;pagging:0"><input title = "' + (newText == "" ? html : newText) + '" type="text" id="' + id + 'displayText" value="' + (newText == "" ? html : newText) + '" /><span style="color:Red; width:100%;" id="' + id + 'displayTextError"></span></span><span style="float:left">' + CreateDropDown('ddl_' + id, valueFormat, hasWeights) + '</span><a class="' + ancClass + '"></a></li>';
}
else {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><a class="' + ancClass + '"></a></li>';
}
return liObject;
}
You can use for loop instead of jQuery.each, that will be faster. Store the itemCount before the loop, and use that:
itemCount = jsonData.items.length;
for(var i = 0; i < itemCount; i++ ) {
...
You can also use use an array instead of string concatenation, like so:
var innerList = [];
... // inside the loop
innerList.push(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
... // after the loop
$("#itemList").html(innerList.join(''));
This will be faster in IE, I'm not sure about other js engines.
These two methods will not make a significant difference, so you should try implementing a client side pagination from json. (Not by hiding and showing divs, by rendering only visible page into the DOM).
Instead of waiting for the loop to end to append your data, why not actively append the data as you process it. This will allow the user to get immediate feedback instead of waiting for the whole thing to process. Other than this, I'd stick with my original comment to page the data.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
$("#itemList").append( '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>');
}
else if (type = "exportall") {
$("#itemList2").append(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
}
controlId++;
}));
Try replacing jQuery.each with a plain old for...in loop. Using jQuery.each adds overhead that you don't need.
Don't concatenate strings inside your loop. Instead, .push them onto an array variable and use .join('') to build the string all at once at the end.
You may need to eliminate CreateLiWithSpans as a separate function in order to fully implement (2).
Changing from using jQuery.each to a standard javascript for loop should speed it up a bit. Make sure that you save the length to a variable like this though:
for(var i = 0, len = jsonObject.AvailableColumns.length; i < len; i++){
var l = jsonObject.AvailableColumns[i];
// Continue with rest of code
}
Probably won't be a huge increase but every little helps.
Also try lowering the number of function calls you make as these have added overhead (not usually an issue, but in a large loop it can help). Unless the code is shared between functions try doing it inline and see how much that speeds it up.

Categories

Resources