Compare HTML element with JSON array and replace - javascript

So I've been trying this for a while but no luck so far. What I want to achieve is, after selecting a value from the drop down, that value should be compared with the json multi-dimensional array. If it matches, then there are certain html elements on the webpage whose content needs to be replaced with the corresponding json values.
Here is the what I've been working so far (link)
<select onchange="executeMe(this)" id="selectOpt">
<option value="445">Choose...</option>
<option value="445">Daisy</option>
<option value="446">Romeo</option>
</select>
<br/><br/><br/>
<label id="entity_id">replaceThis</label>
So in the fiddle, if the user chooses "Daisy" from the dropdown, (the first array has Daisy in it) the corresponding value set from the array should be displayed in each of the html element on the webpage.
I can use only javascript for this. Thanks in advance guys...

You've got problems. First, your string you get back from your map function is massive and certainly won't pass an equality check with your option value. Additionally, your anonymous function is going to return the first value and not iterate through your for loop properly. There's no correlation between your select option values/labels and the items in the array. Try this:
function executeMe(select) {
var myselect = document.getElementById("selectOpt");
var selectOption = myselect.options[myselect.selectedIndex].innerHTML;
var i = theArray.length, obj, index, val;
while (i--) {
obj = theArray[i];
for (index in obj) {
val = obj[index];
//following matches on both keys and values, if you only
//want values delete the second part of the check
if (val == selectOption || index == selectOption) {
var string = '', prop;
for (prop in obj) {
string += prop + ': ' + obj[prop].toString() + '<br>';
}
document.getElementById('entity_id').innerHTML = string;
}
}
}
}
If this isn't what you need let me know with a comment.

Related

get values from json variable data with jquery or javascript

The json output is some thing like:
{"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}
I need to do an append with each of the received values. The numbers next to them are how many times they exist.
I know it will probably be something with "for each" value, but, since the values and keys of the json response are variable, it's difficult for me how to figure out the way to do it.
I will like that the append order depends on how big the number is. If it's bigger print it on the top, and so on...
for example:
<div id="values">
<p>The value "more" is repeated 5 time(s).</p>
<p>The value "apple" is repeated 3 time(s).</p>
<p>The value "another" is repeated 1 time(s).</p>
...
</div>
Remember! The response can change, the response won't be always apple, another, more, volvo, audi and ford... It can CHANGE!
EDIT:
I can do something with this, but, how do I order them with higher or lower values?
for (var key in interests) {
if (interests.hasOwnProperty(key)) {
console.log(key + " -> " + interests[key]);
}
}
EDIT:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}; // initial data
var interestsValue = []; // data with values
for (var key in data){ interestsValue.push({ name: key, value: data[key] }); } // send data with values
interestsValue.sort(function(a, b){ return b.value - a.value; }); // sort values
console.log(interestsValue); // values ordered from bigger to smaller
First - convert the object to a valid array:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
var arr = [];
for (var key in data)
{
arr.push({ name: key, value: data[key] });
}
Then.... use that array with jQuery, angular, etc... to populate your elements
Enjoy :)
Like this.Loop through your objcet using jquery's $.each method Then append the html into your div with append method.
var obj= {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
text = "";
$.each(obj,function(index,element){
text +=" <p>The value " +index+ " is repeated "+ element + " time(s).</p>";
});
$("#values").append(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
JS fiddle https://jsfiddle.net/uobedcf0/
See UPDATED Fiddle:
https://jsfiddle.net/u1kn6d6L/1/
As mention above first convert object into the array.
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
function sortByValue (data){
var dataArray=[];
for(var key in data){
dataArray.push({name:key ,value :data[key]});
}
dataArray.sort(function(a,b){return b.value- a.value}); //sort it in descreasing order
return dataArray;
}
var text="";
var objArray = sortByValue(data);
$.each(objArray,function(index,object){
text +=" <p>The value " +object.name+ " is repeated "+ object.value + " time(s).</p>";
});
$("#values").append(text)

Populate a html dropdownlist from a comma delimted JSON object with distinct values

I have a JSON object that returns several key value pairs. One of which is a Languages key and this contains comma separated values e.g "English, Hindi,French" etc
What I require is to get the distinct values from the Language keys value and then into the following dropdown list.
The following is inputing the Language values into a dropdown but not handling the comma separating values, can someone help please.
Select a language_
$('#combolist-languages').html(function () {
var ret = '<option value="-1" selected>Select language_</option>',
u = user.slice(),
arr = [];
(function get() {
if (u.length) {
var v = u.shift();
if ($.inArray(v.Languages, arr) == -1) {
arr.push(v.Languages);
ret += '<option value="">' + v.Languages + '</option>';
}
get();
}
}());
return ret;
});
Example link -
31.222.187.42/hca-consulting/Farm/index.html
NOTE the following returns all the records from the db: Search by Name > Browse Names
You can use javascript spilt function and put the values into the array then pass it to the dropdown list.
For json key value pairs you can separate by "."

Best way to populate select list with JQuery / Json?

Currently our dev team uses this pattern, but I can't help but wonder if there is a faster or more html-efficient way of accomplishing the same task.
HTML
<select id="myList" style="width: 400px;">
</select>
<script id="myListTemplate" type="text/x-jQuery-tmpl">
<option value="${idField}">${name}</option>
</script>
And this is the Javascript:
function bindList(url) {
callAjax(url, null, false, function (json) {
$('#myList').children().remove();
$('#myListTemplate').tmpl(json.d).appendTo('#myList');
});
}
This is a function I wrote to do just that. I'm not sure if it's faster than jQuery Templates. It creates and appends the Option elements one at a time, which may be slower than Templates. I suspect that Templates builds the whole HTML string, and then creates the DOM elements all in one shot. That may be a faster. I suppose this function could be adjusted to do the same thing. I've worked with Templates, and I do find that this function is easier to consume for something a simple as populating a Select list, and it fits nicely into my utility.js file.
Update: I updated my function to build the HTML first, and call append() only once. It actually runs much faster now. Thanks for posting this question, it's nice to be able to optimize one's own code.
Consuming the function
// you can easily pass in response.d from an AJAX call if it's JSON formatted
var users = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Cindy'} ]
setSelectOptions($('#selectList'), users, 'id', 'name');
The function code
// Fill a select list with options using an array of values as the data source
// #param {String, Object} selectElement Reference to the select list to be modified, either the selector string, or the jQuery object itself
// #param {Object} values An array of option values to use to fill the select list. May be an array of strings, or an array of hashes (associative arrays).
// #param {String} [valueKey] If values is an array of hashes, this is the hashkey to the value parameter for the option element
// #param {String} [textKey] If values is an array of hashes, this is the hashkey to the text parameter for the option element
// #param {String} [defaultValue] The default value to select in the select list
// #remark This function will remove any existing items in the select list
// #remark If the values attribute is an array, then the options will use the array values for both the text and value.
// #return {Boolean} false
function setSelectOptions(selectElement, values, valueKey, textKey, defaultValue) {
if (typeof (selectElement) == "string") {
selectElement = $(selectElement);
}
selectElement.empty();
if (typeof (values) == 'object') {
if (values.length) {
var type = typeof (values[0]);
var html = "";
if (type == 'object') {
// values is array of hashes
var optionElement = null;
$.each(values, function () {
html += '<option value="' + this[valueKey] + '">' + this[textKey] + '</option>';
});
} else {
// array of strings
$.each(values, function () {
var value = this.toString();
html += '<option value="' + value + '">' + value + '</option>';
});
}
selectElement.append(html);
}
// select the defaultValue is one was passed in
if (typeof defaultValue != 'undefined') {
selectElement.children('option[value="' + defaultValue + '"]').attr('selected', 'selected');
}
}
return false;
}

Populate dropdown select with array-with multiple options

So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text.
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...];
$.each(states, function(val, text) {
$('#selector').append( $('<option> </option>').val(val).html(text) )
});
Try this, using an object for states instead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation:
var states = {
"Select State":"",
"Alabama":"AL",
"Alaska":"AK",
"Arizona":"AZ",
"Arkansas":"AR"
};
var val, text;
for (text in states) {
val = states[text];
$('<option/>').val(val).text(text).appendTo($('#selector'));
};
http://jsfiddle.net/g59U4/
The problem is that the callback function provided to .each results in val containing the index of the current iteration (e.g. 0, 1, 2 etc.) and text containing the value of that index of the array.
To achieve what you are trying to, you would probably be better off with a normal for loop:
for(var i = 0; i < states.length; i+=2) {
$("#selector").append($('<option> </option>').val(states[i+1]).html(states[i]));
}
You would be even better off caching the jQuery object containing #selector outside of your loop, so it doesn't have to look it up every iteration.
Here's a working example of the above.
Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like #mblase75 has done
Well you have the jQuery.each function arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like:
$.each(states, function(index) {
if(index%2 > 0) {
//continue, basically skip every other one. Although there is probably a better way to do this
return true;
}
$('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) )
});
That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this:
var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"];
for(var i=1; i<states.length; i+=2) {
$('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) )
}
If you changed your array to be an array of objects, you could do something like this -
var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc
$.each(states, function(val, statedata) {
$('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) )
});
This change passes a JavaScript object in to the callback each time. The object has text and val properties and is passed in to the callback as the statedata parameter. The val parameter holds the current index position of the array so it is not required to populate the select box.
Demo - http://jsfiddle.net/sR35r/
I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback ....
JSON ...
[["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ...
var stateOptions = $('#state');
var html ='';
for (var i =1; i<data.length; i++){
html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';
}
stateOptions.append(html);
<form name="form" id="form">
<select name="state" id="state">
<option value=''>State</option>
</select>
</form>

Generic way to fill out a form in javascript

I'm looking for a really generic way to "fill out" a form based on a parameter string using javascript.
for example, if i have this form:
<form id="someform">
<select name="option1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="option2">
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
I'd like to be able to take a param string like this: option1=2&option2=1
And then have the correct things selected based on the options in the query string.
I have a sort of ugly solution where I go through children of the form and check if they match the various keys, then set the values, but I really don't like it.
I'd like a cleaner, generic way of doing it that would work for any form (assuming the param string had all the right keys).
I'm using the prototype javascript library, so I'd welcome suggestions that take advantage of it.
EDIT: this is what I've come up with so far (using prototype for Form.getElements(form))
function setFormOptions(formId, params) {
params = params.split('&');
params.each(function(pair) {
pair = pair.split('=');
var key = pair[0];
var val = pair[1];
Form.getElements(form).each(function(element) {
if(element.name == key) {
element.value = val;
}
});
});
}
I feel that it could still be faster/cleaner however.
If you're using Prototype, this is easy. First, you can use the toQueryParams method on the String object to get a Javascript object with name/value pairs for each parameter.
Second, you can use the Form.Elements.setValue method (doesn't seem to be documented) to translate each query string value to an actual form input state (e.g. check a checkbox when the query string value is "on"). Using the name.value=value technique only works for text and select (one, not many) inputs. Using the Prototype method adds support for checkbox and select (multiple) inputs.
As for a simple function to populate what you have, this works well and it isn't complicated.
function populateForm(queryString) {
var params = queryString.toQueryParams();
Object.keys(params).each(function(key) {
Form.Element.setValue($("someform")[key], params[key]);
});
}
This uses the Object.keys and the each methods to iterate over each query string parameter and set the matching form input (using the input name attribute) to the matching value in the query params object.
Edit: Note that you do not need to have id attributes on your form elements for this solution to work.
Try this:
Event.observe(window, 'load', function() {
var loc = window.location.search.substr(1).split('&');
loc.each(function(param) {
param = param.split('=');
key = param[0];
val = param[1];
$(key).value = val;
});
});
The above code assumes that you assign id values as well as names to each form element. It takes parameters in the form:
?key=value&key=value
or
?option1=1&option2=2
If you want to keep it at just names for the elements, then try instead of the above:
Event.observe(window, 'load', function() {
var loc = window.location.search.substr(1).split('&');
loc.each(function(param) {
param = param.split('=');
key = param[0].split('_');
type = key[0];
key = key[1];
val = param[1];
$$(type + '[name="' + key + '"]').each(function(ele) {
ele.value = val;
});
});
This code takes parameters in the form of:
?type_key=value&type_key=value
or
?select_option1=1&select_option2=2
You said you're already going through the elements and setting the values. However, maybe this is cleaner that what you have?
function setFormSelectValues(form, dataset) {
var sel = form.getElementsByTagName("select");
dataset.replace(/([^=&]+)=([^&]*)/g, function(match, name, value){
for (var i = 0; i < sel.length; ++i) {
if (sel[i].name == name) {
sel[i].value = value;
}
}
});
}
You could then adapt that to more than just select elements if needed.
Three lines of code in prototype.js:
$H(query.toQueryParams()).each(function(pair) {
$("form")[pair.key].setValue(pair.value);
});
You can get form data in JavaScript object using formManager .

Categories

Resources