Get list of elements using data-id - javascript

I must have a list of label elements with data-id attrib where I use labels values to set img on the main container.
Function changeimage was return nodelist with null elements but I don't have any idea why
Any solutions ?
function getState() {
try {
$.ajax({
type: "POST",
url: "Default.aspx/jsrequest",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ajax").empty();
$.each(data, function () {
$("#ajax").append('<div id="ajaxcontent">
</div>');
$("#ajaxcontent").addClass("ajaxcontent");
$.each(this, function (k, v) {
$("#ajaxcontent").append('<div class="view">'
+ ' <label id="IdOfMachine">'
+ v.MachineId
+ '</label>'
+ '<label class="MachineState" data-id= "'
+ v.MachineId + ' " > '
+ v.CurrentStatus
+ '</label > '
+ '<img id="ChangeImg" src="">'
+ '</img>'
+ '<label id="MachineName">'
+ v.MachineName
+ '</label>'
+ '</div>');
});
});
},
error: function (response) {
alert("something wrong")
}
});
} catch (err) { }
}
window.onload = function () {
getState();
setInterval(function () {
getState();
}, 20000);
}
function ChangeImage() {
let labels = document.querySelectorAll(["data-id"]);
//here i need to loop over element list and then get lables values to set img which show current state of label
}

You could change it to something like this:
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function(i, x) {
var text = $(x).text();
});
}
This should provide you with the text from the label equal to v.CurrentStatus
demo
function ChangeImage() {
let labels = $('label[data-id]');
$.each(labels, function(i, x) {
var text = $(x).text();
console.log(text);
});
}
ChangeImage()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label data-id="1">test1</label>
<label data-id="2">test2</label>

Why not using css selector
function ChangeImage() {
let labels = $('.MachineState').map(() => {
let item = {
id: $(this).data('id'),
value: $(this).text()
}
let imgUrl = `${item.id}-${item.value}.jpg` // for example
$(this).closest('img').attr('src', imgUrl)
return item
});
}
This will generate list of object like this
[{id: 1, value: 'label1'}, {id: 2, value: 'label2'}, ...]

Related

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 can I pass a variable for formatResult and formatSelection (select2)?

For example, I have a class:
classA.js
$(document).ready(function() {
select2_scroll('element_name_id')
});
calling a function from
classB.js
function select2_scroll(elementId, queryString) {
resource_url: 'something/';
$('#' + elementId).select2({
allowClear: true,
ajax: {
url: resource_url,
dataType: 'json',
type: 'GET',
quietMillis: 100,
data: function (term, page) {
return {
search_term: term,
page: page
};
},
results: function (data, page) {
var more = (page * PAGE_LIMIT) < data.total_results;
return { results: data.resource, more: more };
}
},
formatResult: resourceName,
formatSelection: resourceName,
});
}
function resourceName(resource) {
var format = '<div>' + resource.name + '</div>' +
'<input type="hidden" name="' + elementId + '_id" value="' + resource.id + '"/>';
return format;
}
How do I avoid using a global variable to pass the elementId variable? I can't call resourceName directly and pass the elementId in by calling resourceName(resource, elementId).
Am I missing something from the Select2 component?
You could try something like :
formatResult: ()=>{
resourceName(resource, elementId);
},
formatSelection: ()=>{
resourceName(resource, elementId);
},
Add your element Id in your "results" return
results: function (data, page) {
var more = (page * PAGE_LIMIT) < data.total_results;
return { results: data.resource, more: more, elementId: elementId };
}
And use it in your function:
var format = '<div>' + resource.name + '</div>' +
'<input type="hidden" name="' + resource.elementId + '_id" value="' + resource.id + '"/>';
Let me know, if this works for you. I didn't have tested it with your example
I found a solution to my problem. I can just do
...
formatResult: function(resource) {
return resourceName(resource, elementId)
},
formatSelection: function(resource) {
return resourceName(resource, elementId)
},
....
Thanks!

jQuery Select2 - Select ajax-submitted value

I have a form that submits a new entry via ajax and returns the entry data. I'm trying to get the returned data to be automatically selected in the Select2 field. I can get the id entered as the input value, but I'm not sure how to get the text to be displayed in the span.
Here's the JS I have so far:
function clientFormatResult(client){
var markup = client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
return markup;
}
function clientFormatSelection(client) {
$('#client-input').empty();
$('#client-input').append('<input type="hidden" name="client" value="' + client.id + '" />');
return client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
}
$('#client-selection').select2({
placeholder: 'Select a client',
allowClear: true,
minimumInputLength: 1,
ajax: {
type: 'POST',
url: 'clients/get_client_list',
dataType: 'json',
data: function (term) {
return {filter: term};
},
results: function (data) {
return {results: data};
}
},
formatResult: clientFormatResult,
formatSelection: clientFormatSelection,
dropdownCssClass: 'bigdrop',
initSelection: function (element, callback) {
var id = element.val();
if(id != '') {
$.ajax('clients/get_client_list/'+id).done(function(data) {
data = $.parseJSON(data);
callback(data);
});
}
}
});
$('#add-client-form').submit(function(e) {
e.preventDefault();
var form = $(this),
url = form.attr('action'),
data = form.serialize();
$.post(url, data, function(data, status, xhr) {
$('.form-response').fadeOut(400);
if(status == 'success') {
$('#add-client-modal').modal('hide');
data = $.parseJSON(data);
$('#client-selection').select2('val', data.client_id);
} else {
$('#add-client-failure').fadeIn(400);
}
});
});
As you can see, the text displayed is meant to be like "John Smith (smithj)".
I sorted it out, it was an issue with the data I was returning. Select2 was expecting an id variable, but I was returning it as client_id.

Append returned data to different elements based on objects names

How do you append json returned objects to different elements based on the object's name? My JSON data is bigger than the following example so I wonder if it's a good idea to use if statement in .ajax for each object:
JSON Example Data
[{"name":"Europe","year":"2000"},{"name":"Asia","year":"2001"},{"name":"Africa","year":"2002"}]
HTML
<div class="Europe"></div>
<div class="Asia"></div>
<div class="Africa"></div>
JS
$.ajax({
url: "text.json",
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var name = item.name;
item_html='<h3>'+name+'</h3><div>'+item.year+'</div>';
});
if (name == Africa){
$('.Africa').append(item_html);
}
if (name == Europe){
$('.Europe').append(item_html);
}
if (name == Asia){
$('.Asia').append(item_html);
}
},
error: function () {$('.Europe').append("<b>No Results Returned</b>");}
});
Move your if block in each
$(data).each(function (index, item) {
var name = item.name;
item_html = '<h3>' + name + '</h3><div>' + item.year + '</div>';
if(name == 'Africa') {
$('.Africa').append(item_html);
}
if(name == 'Europe') {
$('.Europe').append(item_html);
}
if(name == 'Asia') {
$('.Asia').append(item_html);
}
});
I think since the name and class names are the same you can use it to find the target element within the .each() loop and set its content like
$.ajax({
url: "text.json",
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var name = item.name;
$('.' + name).html('<h3>' + name + '</h3><div>' + item.year + '</div>')
});
},
error: function () {
$('.Europe').append("<b>No Results Returned</b>");
}
});

How to list values in Jquery

I have a JSON data which is sent to getJSON method. JSON data is
[{"Name":"P1","Description":"D1","Attribute":"E,S","Value":"EV,SV"}]
and getJSON method
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});
I would like to get the alert as
E : EV
S : SV
The code here is assuming you have the pair in order. The idea is split the attribute and value, then select the value with same index to alert.
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
$.each(data, function (k, v) {
var attrs = v.Attribute.split(",");
var values = v.Value.split(",");
for(var i = 0; i < attrs.length ; i++)
{
alert(attrs[i] + " : " + values[i]);
}
});
});
});
try this
$.getJSON(url, { Name: 'P1' }, function (data) {
var aSplit=data[0].Attribute.split(',');
var vSplit=data[0].Value.split(',');
alert(aSplit[0] + ' : ' + vSplit[0]);
alert(aSplit[1] + ' : ' + vSplit[1]);
});
If data is coming as string, then you need to eval(data) to get a javascript object.
Try :
$(document).ready(function () {
$.getJSON(url, { Name: 'P1' }, function (data) {
data = eval('('+data+')');
$.each(data, function (k, v) {
alert(v.Attribute + ' : ' + v.Value);
});
});
});

Categories