I am trying to extract data from the option value. For example only ID or UserName. Can you please help?
$(document).ready(function() {
$.getJSON("http://localhost:8080/EBCargoAndCommodityServices/resources/user-form/retrieve", function(data) {
data.forEach(function(dt) {
$("#customer-list").append('<option value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
});
$('#customer-list').change(function() {
var str = this.value;
alert(str);
});
});
});
Let's say for example that dt.id = 1 and dt.contactName is Bartosz.
So you would be alerting 1Bartosz in alert(str)
While building up the options do this,
$("#customer-list").append('<option value="' + `${dt.id}_${dt.contactName}` + '">' + dt.contactName + '</option>'); // Using template literals and concatenating both id and contact name using a delimiter `_`
Then, in your change function do this.
const info = str.split('_')
/*
info will be an array with two elements
info[0] will be id i.e. 1
info[1] will be contactName i.e. Bartosz
*/
Sure you can, the best way would be to store the values you need to use into specific data attributes, then access them using the .data() method
const $ = jQuery;
$(document).ready(function() {
// Mocked data for test
const data = [{"address":"","companyName":"","contactName":"ghkkkkk","email":"","id":22,"surname":"","telephone":0},
{"address":"","companyName":"","contactName":"asdasd","email":"","id":23,"surname":"","telephone":0}]
data.forEach(function(dt) {
$("#customer-list").append('<option data-id="' + dt.id + '" data-name="' + dt.contactName + '" value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
});
$('#customer-list').change(function() {
const selected = $(this).find('option:selected');
$('#result').text('selected id is: ' + selected.data('id') + ' contact name is : ' + selected.data('name'))
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="customer-list">
<option>select an option</option>
</select>
<span id="result"></span>
Related
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();
});
});
I am using jQuery to generate some input fields and buttons on the fly. I provide an ID attributes for these elements, which are also dynamically generated using an algorithm:
// Where menuItem is a string (ex. 'Child Admission' -> 'Child_AdmissionQuantity')
var quantityId = menuItem.replace(' ', '_') + 'Quantity';
I then use the same algorithm to select the field using jQuery and attempt to get the value of the input field:
// Get Reference to the quantity field
var quantityId = '#' + menuItem.replace(' ', '_') + 'Quantity';
console.log("quantityId: " + quantityId);
// Get the Value of the field
var quantity = $(quantityId).val();
Instead of returning a string, jQuery returns a [object HTMLInputElement].
Here is how I create the form fields:
function processMenuItem(menuItem) {
// Generate a quantityId
var quantityId = menuItem.replace(' ', '_') + 'Quantity';
console.log("menuItem: " + menuItem + "\n"
+ "quantityId: " + quantityId + "\n");
// Generate a Menu Item Option
var menuItemOption = '<div class="product">'
+ '<div class="productName">' + menuItem + '</div>'
+ '<div class="quantity">'
+ '<input type="text" name="quantity" id="' + quantityId + '" placeholder="2" />'
+ '</div>'
+ '<button type="button" onclick="addItem(\'' + menuItem + '\')">Add Item</button>'
+ '</div><!-- End of .product -->';
// Add the Option to the Menu
$('#displayMenu').append(menuItemOption);
}
I need the actual value for form processing, anyone know a work around?
Thanks!
I am trying to make a select with the option value and text coming from two separate arrays (one is called like_list and the other like_list_name). The '$.each' joins two arrays and makes list of options. When I look in console.log I can see the options looking good:
$.each(like_list, function(i, item) {
console.log('<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>');
});
But when I name the output as 'optionlist' and try to put 'optionlist' into the div 'friendselect' with Inner HTML it doesn't work:
var optionlist = $.each(like_list, function(i, item) {
'<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>';
});
document.getElementById('friendselect').innerHTML = '[select]' + optionlist + '[/select]';
Is there anyway to get this select box into the 'friendselect' div? NOTE: i USED '[' because the side arrow wasn't working.
You should try with map function:
var optionlist = $.map(like_list, function(i, item) {
return '<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>';
}).join('');
document.getElementById('friendselect').innerHTML = '<select>' + optionlist + '</select>';
$.each() doesn't return the values in it's function, you will have to add them toghether yourself.
The best thing you can do is add the options to the select in the each loop like so:
$.each(like_list, function(i, item) {
$("#friendselect").append('<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>');
});
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.
I need to modify some code already in place. There's a block of code that filters a JQuery list using the URL to populate the search input.
E.g.
http://***/store/mobile/page/productList.page?search=football
Automatically enters "football" in the search bar.
Now I'd need to filter the list, without using the search bar.
So lets say my URL would look something like this :
http://***/store/mobile/page/productList.page?football
This would filter the list with football without using the search bar.
Here's the code I need to change. Please tell me if my question is unclear.
$('div[data-url*="productList"]').live("pageshow", function() {
filterValue = getParameterByName("search", location.search);
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
});
and:
$.each(catalog.products,
function(index, value) {
if ((!filterValue )
|| value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.brand.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
{
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p>' + value.brand + '</p>' +
'<h3>' + value.name + '</h3>' +
'<span class="ui-li-count">' + value.price + ' $</span></li>') +
'</a>';
}
});
if there will always be only 1 parameter after ? than you could simply get it from page location in javascript, e.g.
var url = document.location;
var params = url.split("?");
filterValue = params[params.length-1]
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
example: http://jsfiddle.net/yPgPc/