Create search list based on data from array - javascript

I have an array that should be used to create a list of search engines next to a search field.
I have this script which is working. However, it generates a select box of options - you enter a search phrase, select engine, and then get a result. However, since I have to change the markup to be using Bootstrap, I need to change the select box to an unordered list, like this:
<ul class="dropdown-menu">
<li class="selected">Select</li>
<li>Google</li>
<li>Nyheder</li>
<li>Studier</li>
</ul>
If I try to change the select into <ul id="global_search_filter" class="search_filter"></ul> and var option = jQuery(document.createElement("option")); to var option = jQuery(document.createElement("li"));the scripts breaks.
How can I achieve the same functionality but change the markup from a select box to an unordered list with list options?
I have created a fiddle here.
Maybe someone can point me in the right direction on how to solve this.
el = document.getElementById("localdomain");
el.value = window.location.hostname;
if (!window.searchEngines) {
window.searchEngines = [{
"url": "https://www.google.com",
"label": "Google",
"querykey": "q",
"id": "allWeb"
}, {
"url": "https://www.bing.com",
"label": "Bing",
"querykey": "q",
"id": "bing",
"param": {
"doctype": "",
"path": "",
"cms_mode": ""
}
}, {
"url": "https://www.yahoo.com",
"label": "Yahoo",
"querykey": "q",
"id": "yahoo",
"param": {
"gcse": "014167723083474301078:sxgnobjpld4"
}
}];
}
window.searchCallbacks = [];
jQuery(function() {
var stripPath = function(path) {
return path === "/" ? path : path.replace(/\/$/, "");
};
var isEngineCurrent = function(engine) {
if (stripPath(engine.url) !== stripPath(document.location.origin + document.location.pathname)) {
return false;
}
if (engine.param) {
for (var key in engine.param) {
if (getUrlParameter(key) !== engine.param[key]) {
return false;
}
}
}
return true;
};
var forms = jQuery("form.search_form");
forms.each(function() {
var form = jQuery(this);
var field = form.find("input.search_query");
var filter = form.find(".search_filter");
var resetForm = form.hasClass("search_reset");
if (window.searchEngines) {
for (var i = 0; i < window.searchEngines.length; i++) {
var engine = window.searchEngines[i];
var option = jQuery(document.createElement("option"));
option.text(engine.label);
option.val(i);
if (!resetForm && isEngineCurrent(engine)) {
option.attr("selected", "selected");
field.val(getUrlParameter(engine.querykey));
}
filter.append(option);
}
form.submit(function(event) {
var chosenEngine = window.searchEngines[filter.val()];
form.attr("action", chosenEngine.url);
form.attr("method", chosenEngine.method || "GET");
field.attr("name", chosenEngine.querykey);
if (chosenEngine.param) {
for (var paramName in chosenEngine.param) {
var input = jQuery(document.createElement("input"));
input.attr("type", "hidden");
input.attr("name", paramName);
input.val(chosenEngine.param[paramName]);
form.append(input);
}
}
for (var i = 0; i < window.searchCallbacks.length; i++) {
var callback = window.searchCallbacks[i];
if (jQuery.isFunction(callback)) {
callback(chosenEngine, this);
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="global_search_form" class="search_form search_reset" target="_blank">
<input type="text" id="global_search_query" class="search_query" placeholder="Search where...?">
<input id="localdomain" name="localdomain" type="hidden" value=" + window.location.hostname + ">
<select id="global_search_filter" class="search_filter"></select>
<button name="sa" id="submit-button" type="submit">Search</button>
</form>

Working Jsfiddle.
Here is a modified version of your code(unfortunately you can't submit a form on Stack Overflow, but you can test the jsfiddle above). Will update imediatelly with explications:
UPDATE:
Ok, so let's see what we have done here:
First we replace the select with an ul container
We append li elements to the ul parent
We add the data-selected custom attribute on every li element with empty value except the first one which we add the selected value.
We add the data-value attribute to the li element to replicate the value like when we have a select option value.
On click of a dynamically added li element we bind the click event dinamically using event delegation to add the selected attribute value.
On click of the li element we also add the selected value name to the Bootstrap button.
el = document.getElementById("localdomain");
el.value = window.location.hostname;
if (!window.searchEngines) {
window.searchEngines = [{
"url": "https://www.google.com",
"label": "Google",
"querykey": "q",
"id": "allWeb"
}, {
"url": "https://www.bing.com",
"label": "Bing",
"querykey": "q",
"id": "bing",
"param": {
"doctype": "",
"path": "",
"cms_mode": ""
}
}, {
"url": "https://www.yahoo.com",
"label": "Yahoo",
"querykey": "q",
"id": "yahoo",
"param": {
"gcse": "014167723083474301078:sxgnobjpld4"
}
}];
}
window.searchCallbacks = [];
jQuery(function() {
var stripPath = function(path) {
return path === "/" ? path : path.replace(/\/$/, "");
};
var isEngineCurrent = function(engine) {
if (stripPath(engine.url) !== stripPath(document.location.origin + document.location.pathname)) {
return false;
}
if (engine.param) {
for (var key in engine.param) {
if (getUrlParameter(key) !== engine.param[key]) {
return false;
}
}
}
return true;
};
$(document).on('click', 'li', function() {
$('li[data-selected="selected"]').attr('data-selected', '');
$(this).attr('data-selected', 'selected');
$("#menu").text($(this).text());
$("#menu").val($(this).text());
})
var forms = jQuery("form.search_form");
forms.each(function() {
var form = jQuery(this);
var field = form.find("input.search_query");
var filter = form.find(".dropdown-menu");
var resetForm = form.hasClass("search_reset");
if (window.searchEngines) {
for (var i = 0; i < window.searchEngines.length; i++) {
var engine = window.searchEngines[i];
var option = jQuery(document.createElement("li"));
option.text(engine.label);
option.attr('data-value', i);
if (i == 0) {
option.attr('data-selected', 'selected');
} else {
option.attr('data-selected', '');
}
option.attr('role', 'presentation');
if (!resetForm && isEngineCurrent(engine)) {
option.attr("selected", "selected");
field.val(getUrlParameter(engine.querykey));
}
filter.append(option);
}
form.submit(function(event) {
var chosenEngine = window.searchEngines[$('li[data-selected="selected"]').data('value')];
console.log(chosenEngine);
form.attr("action", chosenEngine.url);
form.attr("method", chosenEngine.method || "GET");
field.attr("name", chosenEngine.querykey);
if (chosenEngine.param) {
for (var paramName in chosenEngine.param) {
var input = jQuery(document.createElement("input"));
input.attr("type", "hidden");
input.attr("name", paramName);
input.val(chosenEngine.param[paramName]);
form.append(input);
}
}
for (var i = 0; i < window.searchCallbacks.length; i++) {
var callback = window.searchCallbacks[i];
if (jQuery.isFunction(callback)) {
callback(chosenEngine, this);
}
}
});
}
});
});
li[data-selected="selected"] {
color: #F00;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form id="global_search_form" class="search_form search_reset" target="_blank">
<input type="text" id="global_search_query" class="search_query" placeholder="Search where...?">
<input id="localdomain" name="localdomain" type="hidden" value=" + window.location.hostname +">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="menu" data-toggle="dropdown">Choose option
<span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu">
</ul>
</div>
<button name="sa" id="submit-button" type="submit">Search</button>
</form>

Related

Search for duplicate before adding to list

I'm trying to search for duplicates in a list before adding there any information. Could you please take a look at my code and tell me what I'm doing wrong. Thank you!
Another question is how could I iterate arrayList using Object.entries(arrayList)-loop and get the same result as I got w/o using it? When I tried to use Object.entries I was only able to see 0 [object Object], 1 [object Object] instead of names and genders.
let arrayList = [{
"name": "Brandon",
"gender": "M"
},
{
"name": "Charlotte",
"gender": "F"
},
];
let btn = document.getElementById("btn");
btn.onclick = function() {
let showHere = document.getElementById("showHere");
for (let i = 0; i < arrayList.length; i++) {
let li = document.createElement('li');
let text = `${arrayList[i].name} ${arrayList[i].gender}`;
let insert = document.createTextNode(text);
if (arrayList[i].name.indexOf(li) != -1) {
alert(`${arrayList[i].name} already in list`);
} else {
li.appendChild(insert);
showHere.appendChild(li);
}
console.log(li);
}
}
<button type="button" id="btn">Show list</button>
<ul id="showHere"></ul>
Okay I'm not 100% sure what you intended but, you may consider instead of checking for duplicates, clearing out the array before re-rendering it with new values. I modified your snippet so you can see what I'm talking about.
If you have any questions feel free to make a comment!
[Edit] I added a little snippet to check if a name gender combo already exists before adding it to the list.
let arrayList = [{
"name": "Brandon",
"gender": "M"
},
{
"name": "Charlotte",
"gender": "F"
},
];
let btn = document.getElementById("btn");
const addBtn = document.getElementById('add');
addBtn.onclick = function() {
const name = document.getElementById('name').value;
const gender = document.getElementById('gender').value;
// check if value already exists
if(!arrayList.find(obj => JSON.stringify(obj) === JSON.stringify({name, gender}))){
arrayList.push({
name,
gender
});
} else {
console.log('name gender combo already exists');
}
}
btn.onclick = function() {
let showHere = document.getElementById("showHere");
showHere.innerHTML = '';
for (let i = 0; i < arrayList.length; i++) {
let li = document.createElement('li');
let text = `${arrayList[i].name} ${arrayList[i].gender}`;
let insert = document.createTextNode(text);
if (arrayList[i].name.indexOf(li) != -1) {
alert(`${arrayList[i].name} already in list`);
} else {
li.appendChild(insert);
showHere.appendChild(li);
}
console.log(li);
}
}
<input type="text" id="name" ></input>
<input type="text" id="gender" ></input>
<button type="button" id="add">Add to list</button>
<button type="button" id="btn">Show list</button>
<ul id="showHere"></ul>

Parse JSON foreach with JS, shows HTML list

I am currently trying to parse a JSON with JavaScript. My issue is that I'd like the output to look like this:
<li>AppName1</li>
<li>AppName2</li>
<!-- and so on... -->
However it just does not work and I don't know how to achieve that. This is the object deserialized from the JSON response:
{
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
}
This is my .js file:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("test").innerHTML = myObj.AppName;
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
This is in my HTML file
<p id="test"></p>
Any help would be appreciated as I really cannot seem to understand this a single bit. Thank you so much!
Firstly note that you can only have li elements as children of <ul> or <ol>, so the p element needs to be changed.
The AppName property is part of the objects within data, so you will need to either loop through them:
myObj.data.forEach(function(o) {
document.getElementById("test").innerHTML += '<li>' + o.AppName + '</li>';
}
Or access them, individually by index:
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>'; // first item only
var myObj = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>';
<ul id="test"><li>
If you just want a list of the AppName properties, you could do something like the below with jQuery. See the comments in the code for details:
// Below is the JSON string from the OP's link
let json = '{"data":[{"AppId":3,"AppName":"AnimojiStudio","AppSlug":"animojistudio","AppIcon":"https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa","AppVersion":"1.2.2","AppSize":"2.1"},{"AppId":2,"AppName":"Cute Cut Pro","AppSlug":"cute-cut-pro","AppIcon":"http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa","AppVersion":"","AppSize":""}]}';
// Parse the JSON string into a JS object
json = JSON.parse(json);
let html = "";
// Loop over the object and append a list item for each AppName property.
$.each(json.data, function (index, item) {
html += "<li>" + item.AppName + "</li>";
});
// Append the list to the div.
$("#container").append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div id="container"></div>
Using forEach loop and append. Inserting li inside a p tag is not a good idea even though it works. Convert the p into a ul/ol
var data = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
data.data.forEach(e =>$('#test').append('<li>' + e.AppName + '</li>' + "<br>"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
You can use map() since you have an array inside myObj. What you want to do is returning a li with AppName value
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var ul = document.getElementById("myUl");
var li = document.createElement('li');
var data = myObj.data;
data.map(app => {
li.textContent = app.AppName;
ul.appendChild(li);
})
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
You have your object, and it is parsed so let's concentrate on doing something with that object:
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
Now we have that, let's use it in different ways. myObj contains an array called data here. That array is an array of JavaScript objects, each with properties like "AppId", "AppName" etc. which we can access either directly or through an index. So, let's put up some examples of how to do that. Comments in the code
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
// Here I create a Bootstrap tab and contents
// call to create a new element on the DOM
function additem(item) {
let lt = $('#list-tab');
let ltc = $('#debug-tabContent');
let thing = item.name;
let thingId = "list-" + thing;
let thingTabId = thingId + "-list";
let ttab = $('<a />')
.addClass('list-group-item list-group-item-action')
.data('toggle', "list")
.prop("id", thingTabId)
.attr('role', 'tab')
.prop('href', '#' + thingId)
.html(item.name);
ttab.appendTo(lt);
let lc = $('<div />')
.addClass('tab-pane fade')
.prop("id", thingId)
.attr('role', 'tabpanel')
.text(JSON.stringify(item.obj));
// .text("test");
lc.appendTo(ltc);
}
// * cheat, put the objects in a bootstrap tab content list
additem({
name: "myObj",
obj: myObj
});
additem({
name: "myObjW",
obj: window["myObj"]
});
additem({
name: "data",
obj: myObj.data
});
additem({
name: "data0",
obj: myObj.data[0]
});
additem({
name: "AppName",
obj: myObj.data[0].AppName
});
// pure JS walk
// Here I create a LI list as a Bootstrap list group
let len = myObj.data.length;
let myP = document.getElementById("test");
let myReg = document.getElementById("mylist-reg");
let newUl = document.createElement("ul");
newUl.classList.add('list-group');
newUl.classList.add('list-group-primary');
for (var i = 0; i < len; i++) {
let newLi = document.createElement("li");
let newContent = document.createTextNode(myObj.data[i].AppName);
newLi.appendChild(newContent);
newLi.setAttribute("id", "app-" + myObj.data[i].AppId); //has to be unique
newLi.setAttribute("class", "list-group-item");
newUl.appendChild(newLi);
}
// put the list after the paragraph
document.body.insertBefore(newUl, myP);
let myLast = document.getElementById("app-2");
myLast.classList.add("active");
//activate the bootstrap tab clicks
$('#list-tab').on('click', 'a', function(e) {
e.preventDefault();
$(this).tab('show');
});
// just do it as strings
let html = "";
for (var i = 0; i < len; i++) {
let textel = "<li id='app-js-" + myObj.data[i].AppId + "'>" + myObj.data[i].AppName + "</li>";
html = html + textel;
}
myReg.innerHTML = html;
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let textel = "<li id='app-jq-" + el.AppId + "'>" + index + ":" + el.AppName + "</li>";
$('#mylist-jq').append(textel);
});
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let elid = 'app-jq2-' + el.AppId;
$("<li />").prop("id", elid).text(el.AppName)
.appendTo('#mylist-jq2');
});
.list-group-item {
border: 1px lime solid
}
.list-item-last {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" />
<ul id="mylist-reg"></ul>
<ul id="mylist-jq"></ul>
<ul id="mylist-jq2"></ul>
<p id="test" class="row">put stuff after here</p>
<div class="row">
<div class="col-4">
<div class="list-group" id="list-tab" role="tablist">
</div>
</div>
<div class="col-8">
<div class="tab-content" id="debug-tabContent">
<div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">Click a tab to see one.</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>

next and previous JSON data with javascript

I' would like to create Next/Previous buttons for json array, but I can't get it to work.
This is the last one I have tried
<div id="text"></div>
<button name="prev">go to previous div</button>
<button name="next">go to next div</button>
<script>
myFunction([
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);
function myFunction(arr) {
var out = "";
var i ;
out = '<p>' + arr[i].text + '</p> <br>';
document.getElementById("text").innerHTML = out;
}
</script>
You can convert json data to string or better say html with $.each like below. as you tagged jQuery, here is jQuery approach:
myFunction([{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);
function myFunction(arr) {
$.each(arr, function(i, v) {
$('#text').append('<div>' + v.text + '</div>');
});
}
var divs = $('.mydivs>div');
var now = 0;
divs.hide().first().show();
$("button[name=next]").click(function(e) {
divs.eq(now).hide();
now = (now + 1 < divs.length) ? now + 1 : 0;
divs.eq(now).show();
});
$("button[name=prev]").click(function(e) {
divs.eq(now).hide();
now = (now > 0) ? now - 1 : divs.length - 1;
divs.eq(now).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="mydivs"></div>
<button name="prev">go to previous div</button>
<button name="next">go to next div</button>
<div id="text">
</div>
<script>
var i = 0;
let arr = [
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
];
setInterval(function myFunction() {
var out = "";
out = '<p>' + arr[i].text + '</p> <br>';
document.getElementById("text").innerHTML = out;
console.log(out);
if (i < arr.length - 1) {
i += 1;
} else {
i = 0;
}
}, 1000)
</script>

How can I populate dropdown values dynamically based on prior selection?

I have 3 dropdowns with some values. I am using JavaScript to pre-populate the first dropdown.
Based on the selected value in 1st dropdown, how can I populate values in the rest 2 dropdowns (using pure javascript)?
I am framing a URL based on the user selected values in 3 dropdowns using function getURL ,but unable to capture the prepopluated product Name in the URL. Why is it showing the value of ProductName as undefined?
Javascript:
<script>
var ProductNameMap = {
"ProductA":[{"version":"1.0.0","fileName":"FileA1.zip","fileName":"FileA11.dmg"},{"version":"1.0.1","fileName":"FileA2.zip","fileName":"FileA22.dmg"}],
"ProductB":[{"version":"3.5.0","fileName":"FileB1.zip","fileName":"FileB11.dmg"},{"version":"4.0.1","fileName":"FileB2.zip","fileName":"FileB21.dmg"}],
"ProductC":[{"version":"1.0.0","fileName":"FileC1.zip","fileName":"FileC11.dmg"},{"version":"1.0.1","fileName":"FileC2.zip","fileName":"FileC21.dmg"}]
};
function PrepopulateProductName()
{
var ProductNameselect = document.getElementById('selProductName');
var i=1;
for (selProductName in ProductNameMap){
ProductNameselect.options[i++] = new Option(selProductName)
}
}
function changeProductName(productNameID)
{
//Need to populate version dropdown of selected Product
}
function changeProductVersion(productVersionID)
{
//Need to populate file name dropdown of selected ProductVersion
}
function getURL() {
var url = "http://abc.def.com";
var pnid = (selProductName == "") ? "0" : selProductName.value;
var psid = (selProductVersion.value == "") ? "0" : selProductVersion.value;
var pfid = (selFileName.value == "") ? "0" : selFileName.value;
url += "/" + pnid;
url += "/" + psid;
url += "/" + pfid;
document.getElementById("text").innerHTML = "Download Link : ";
document.getElementById("myAnchor").innerHTML = url;
document.getElementById("myAnchor").href = url;
document.getElementById("myAnchor").target = "_blank";
}
</script>
HTML:
Product Name:
<select id="selProductVersion" name="selProductVersion"
onchange="changeProductName(this.value);">
<option>--Choose Product Name--</option>
</select>
Product Version:
<select id="selProductVersion" name="selProductVersion"
onchange="changeProductVersion(this.value);">
</select>
File Name:
<select id="selFileName" name="selFileName"></select>
<button onclick="getURL()">Get URL</button>
<p id="text"></p>
<a id="myAnchor"></a>
Loop through the array of details for the product name to get the versions.
The filename property should be an array so you can have multiple files for each version.
var ProductNameMap = {
"ProductA": [{"version": "1.0.0", "fileName": ["FileA1.zip", "FileA11.zip"]}, {"version": "1.0.1", "fileName": ["FileA2.zip", "FileA22.zip"]}],
"ProductB": [{"version": "3.5.0", "fileName": ["FileB1.zip", "FileB11.zip"]}, {"version": "4.0.1", "fileName": ["FileB2.zip", "FileB22.zip"]}],
"ProductC": [{"version": "1.0.0", "fileName": ["FileC1.zip", "FileC11.zip"]}, {"version": "1.0.1", "fileName": ["FileC2.zip", "FileC22.zip"]}]
};
function PrepopulateProductName() {
var ProductNameselect = document.getElementById('selProductName');
var i = 1;
for (var selProductName in ProductNameMap) {
ProductNameselect.options[i++] = new Option(selProductName)
}
}
function changeProductName(productNameID) {
var versionSelect = document.getElementById('selProductVersion');
versionSelect.innerHTML = '<option>--Choose Product Version</option>'; // Remove previous options
var fileSelect = document.getElementById('selFileName');
fileSelect.innerHTML = '<option>--Choose Filename</option>'; // Remove previous options
var versions = ProductNameMap[productNameID];
for (var i = 0; i < versions.length; i++) {
versionSelect.appendChild(new Option(versions[i].version));
}
}
function changeProductVersion(productVersion) {
var productNameID = document.getElementById('selProductName').value;
var fileSelect = document.getElementById('selFileName');
fileSelect.innerHTML = ''; // Remove previous options
var versions = ProductNameMap[productNameID];
for (var i = 0; i < versions.length; i++) {
if (versions[i].version == productVersion) {
var filenames = versions[i].fileName;
for (var j = 0; j < filenames.length; j++) {
fileSelect.appendChild(new Option(filenames[j]));
}
break;
}
}
}
PrepopulateProductName();
Product Name:
<select id="selProductName" name="selProductName" onchange="changeProductName(this.value);">
<option>--Choose Product Name--</option>
</select>
<br>Product Version:
<select id="selProductVersion" name="selProductVersion" onchange="changeProductVersion(this.value);">
</select>
<br>File Name:
<select id="selFileName" name="selFileName"></select>

Find element by data attributes that use "|" as separators

Fiddle Example
HTML markup:
<div data-id='23|24|25'></div>
<div data-id='29|30|31'></div>
Script:
var array = [
{
"mid": "24"
},
{
"mid": "26"
},
{
"mid": "28"
},
{
"mid": "29"
},
{
"mid": "30"
},
{
"mid": "31"
}
];
var item_html ="";
$.each(array,function(i,k) {
item_html = '<h3>'+k["mid"]+'</h3>';
$('div[data-id="'+k["mid"]+'"').append(item_html); ???????????
});
Would it be possible to find the div element if part of the "|" separated value in its data-id matches the mid?
I'm trying to get an output like this:
<div data-id='23|24|25'>
<h3>24</h3>
</div>
<div data-id='29|30|31'>
<h3>29</h3>
<h3>30</h3>
<h3>31</h3>
You should use the *= selector (contains):
$('div[data-id*="'+k["mid"]+'"').append(item_html);
The result you are looking for is something tricky. I have update your code. hope this will help you.
var array = [
{ "mid": "24"},
{"mid": "26"},
{"mid": "28"},
{"mid": "29"},
{"mid": "30"},
{"mid": "31"}
];
$('[data-id]').each(function(){
var $this = $(this), dataArr = $this.data('id').split('|'), i = 0;
for(;i< dataArr.length; i++) {
if(numInObjArr(array,dataArr[i])) {
$this.append('<h3>'+ dataArr[i] +'</h3>');
}
}
});
//function to check number in array object provided above
function numInObjArr(objArr, num){
for (var i = 0, len=objArr.length; i< len; i++){
if(objArr[i]["mid"] == num) {
return true;
}
}
return false;
}
http://jsfiddle.net/EZ56N/73/ to see the working example

Categories

Resources