How to get Selected feature data only? - javascript

I have problem in for loop, as I am calling all the value from the attribute to options, but it has duplicate value so i used set and get function, with that I also want to call the values like district and plot no. but while doing so it returns the last value of attribute table data.
so, how can i get a values with selected feature only?
$(function () {
GetFeatures();
$('#selectds').change(function () {
console.log($(this).find(":selected").attr('tk'));
console.log($(this).find(":selected").attr('pt'));
});
function GetFeatures() {
var options = "";
let mySet = new Set();
$.each(farmdata.features, function (layer, dsdata) {
dsname = dsdata.properties;
console.log(dsname);
mySet.add(dsname.District);
});
//problem in for loop
for (const item of mySet.values()) {
options += "<option value='' tk='" + dsname['Taluka'] + "'pt='" + dsname['Name'] + "'>" + item + ',Gujarat' + "</option>"
}
$("#selectds").html(options);
console.log(options);
}
});

Related

How to stop the value of an .each loop being the same when appending buttons to a website?

var number = 0;
$.getJSON("blogData.json", function(data) {
$.each(data, function (index, entry) {
console.log(index);
$("#posts").append("<h3>" + entry.title + "</h3>");
$("#posts").append("<h4>" + entry.desc + "</h4>");
$("#posts").append("<h4>" + entry.author + "</h4>");
$("#posts").append("<p>" + entry.post + "</p>");
$("#posts").append("<br>");
$("#posts").append('<button onclick=save(number)>Read More</button>');
$("#posts").append("<br><br>");
number++;
});
});
I want to be able to assign a unique value to every button in order to pass this value to other functions. The context of this is a blog stored in a JSON file where the values of the posts are called via index. I wish to be able to view one post individually by clicking on the button for that specific post.
You have used the variable as string type. All what you need is to concatenate the variable's value.
$("#posts").append('<button onclick=save(' + number + ')>Read More</button>');

Getting undefined in dropdown from json content

EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/

iterate over array in jquery

I'm trying to do some validation on a user selecting items from a list. I want to make sure an item is not added twice by checking if the <li> is already in the array. This is what I'm trying and its not working.
$(".List").on("click", "li", function () {
var i = 0;
var checkArr = [];
var div = $("#AddedItems");
var parent = $(this).closest("ul");
var itemtoadd = parent.find("[data-id]").attr("data-id");
var name = parent.find("[data-name]").attr("data-name");
alert(itemtoadd + name);//checking
var itemtoadd = ("<li id = " + itemtoadd + " class = \"itemAdd\">" + name + "</li>");
checkArr.push(itemtoadd); //put one in to check against?
checkArr.forEach(item)
{
if (item == itemtoadd)
alert("this item has already been added");
else {
checkArr.push(itemtoadd);
alert(itemtoadd);
$(itemtoadd).appendTo(div);
}
}
// div.html(itemtoadd);
});
You have at least three problems here:
You aren't using Array.forEach correctly -- it takes a function that takes an item.
Immediately before you do your check, you're adding the item you're looking for. You will always hit the alert case.
You're using checkArr as a local variable -- you're getting an empty array each time you enter the function.
That all being said, you can accomplish your goal without keeping an array at all. I believe you can replace everything from your first alert down with this:
if ($('#' + itemtoadd, div).length == 0) {
itemtoadd = ("<li id = " + itemtoadd + " class = \"itemAdd\">" + name + "</li>");
div.append(itemtoadd);
}
else {
alert("this item has already been added");
}

Named Array Keys using .map() and .get()

I need to output inputs and their values into a div. However, because I need to match the correct labels to the correct inputs, and some fields allow null values, I'm running into matching issues. Using the following code to pull each label/input into an array, and then output:
var inputArr = $('input, select').map(function(){
return "<p>" + $(this).val() + "</p>";
}).get()
var labelArr = $('label').map(function(){
return "<p>" + $(this).text() + "</p>";
}).get()
function setValuesForConfirm() {
//Clear Div Contents
$("#test-output-1, #test-output").html('');
for (var i = 0; i < labelArr.length; i++) {
$("#test-output-1").append(labelArr[i]);
}
for (var i = 0; i < inputArr.length; i++) {
$("#test-output").append(inputArr[i]);
}
}
So if any of the input's are blank, the fields do not match the labels.
My question is, can I name the array keys to the field name or ID in JS using the .map() function as I am currently?
JSFiddle Here
You could create an object using the inputs:
var formObj={};
$('input, select').each(function(){
formObj[this.name]={val: this.value, labelText: $(this).prev('label').text()};
});
then when loop over object can throw together html
$.each(formObj, function(key, item){
var labelHtml='<p>'+item.labelText+'</p>';
var inputHtml='<p>Name: '+ key+', value: '+item.val+'</p>';
/* do something with html*/
})
While what you have seems to work okay to me, .map creates an array and you can only have numeric ordinal keys in arrays in JavaScript, so you would need an object.
var inputArr = {};
$('input, select').each(function(){
inputArr[$(this).attr('name')] = "<p>" + $(this).val() + "</p>";
});
http://jsfiddle.net/Mz9Vy/1/

Implode array not working as expected

Take a look at my code :
// is_array function
function is_array(input){ return typeof(input)=='object'&&(input instanceof Array); }
// Check if cos_in is an array. If is not, create him
if(!is_array(cos_in))
{
var cos_in = new Array();
}
// Onclick function
function cos(pret,box,configuratie)
{
// Create a value (is different on every click; using different box)
cos_in[box] = box + '|||' + pret + '|||' + configuratie + '||||';
// Insert values from array in some div with #cos id
$("#cos").html(cos_in.join('||||'));
}
My problem is that the div with id #cos has from start value "test-empty", and for each time onclick function is executed, the div should have value from function. But is returns an empty div.
Some help please?
Although this code can be improved a lot I tried to fix your first immediate problem here.
Do you want to append the result every time you click? Where is the join for?
Are you trying to join the keys or the values? I assume for now you want the value and not the key.
window.cos_in = window.cos_in && window.cos_in instanceof Array ? window.cos_in : []
// Onclick function
function cos(pret,box,configuratie)
{
// Create a value (is different on every click; using different box)
cos_in.push(box + '|||' + pret + '|||' + configuratie + '||||');
// Insert values from array in some div with #cos id
$("#cos").html(cos_in.join('||||'));
}
Let me iterate a bit to get to something readable/understandable.
Here is a cleaner example of what you're doing. To improve it more I need to know where you're going with your links and parameters.
var cos = (function (cos_in) {
return function cos(pret, box, configuratie) {
// Create a value (is different on every click; using different box)
cos_in.push(box + '|||' + pret + '|||' + configuratie + '||||');
// Insert values from array in some div with #cos id
$("#cos").text(cos_in.join('||||'));
};
}([]));
Here is an example of an object version instead of an array...
var cos = (function (cos_in) {
return function cos(pret, box, configuratie) {
// Create a value (is different on every click; using different box)
cos_in[box] = (box + '|||' + pret + '|||' + configuratie + '||||');
// Insert values from array in some div with #cos id
$("#cos").text(Object.keys(cos_in).join('||||'));
};
}({}));
This is a simple wrapper you could use:
function join(input, str) {
if(typeof(input) === 'object') {
if(input instanceof Array) {
return input.join(str);
} else {
var tmp = [];
for(var x in input) {
if(input.hasOwnProperty(x)) {
tmp.push(input[x]);
}
}
return tmp.join(str);
}
}
return input;
}
/* ... */
$("#cos").html( join(cos_in, '||||') );
However, you really need to differ between languages. JavaScript might not work as you expect it, at least in comparison with PHP.

Categories