I have JSON data and I have two array with cities and countries.When I clicked my input cities are opening automatically but I want to do this too:
if I cliked my input cities must open (this is okey I did it)
but at the same time if I wrote something for example denmark (this is the list of countries) than denmark must seen if is matching.. how can I do that ?
click to see if you see on codepen
var myJSON = '{ "cities":[ "copenhagen", "london", "hamburg" ], "countries":[ "denmark", "norway", "sweden" ] }';
var myObj = JSON.parse(myJSON);
var testInput = document.getElementById("test");
testInput.setAttribute("data-list", myObj.countries)
function showlist() {
}
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('#test').addEventListener("click", function() {
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
}
else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
}
else {
comboplete.close();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
<input id="test" class="dropdown-input" />
What I get from your question is that you want entries from both arrays to show when you type anything. To achieve that use (myObj.cities.concat(myObj.countries)) array instead of myObj.cities or myObj.countries array alone.
Related
Suppose, I have following array of objects successfully sent to handlebars file from my express server:
[
{
"name": "Jon",
"isPositive": true
},
{
"name": "Cercei",
"isPositive": false
}
]
Each time when my button gets clicked, I want to show next element of the array on my view. Is it possible with handlebars? Or do I need something more complex like Vue.js to solve this problem? Here is simple pseudocode I would like to achieve:
<head>
<script>
$(document).ready(() => {
var index = 0;
var currentCharacter = getCurrentCharacter();
start();
});
</script>
</head>
<body>
<h3 id="name"></h3>
<p id="someInfo"> </p>
<button onclick="next()">Next</button>
<script>
function getCurrentCharacter() {
/// somehow access array of objects sent from server
var myCharacters = {{characters}}; // {} used because of handlebars
var character = myCharacters[index];
index += 1;
return character;
}
function start() {
document.getElementById("name").textContent = currentCharacter.name;
/// as you see here, I change my UI based on current object fields/attributes
if (currentCharacter.isPositive) {
document.getElementById("someInfo").style.display = "block";
document.getElementById("someInfo").textContent = "Some text here";
} else {
document.getElementById("someInfo").style.visibility = "hidden";
}
}
function next() {
currentCharacter = getCurrentCharacter();
start();
}
</script>
</body>
Is it possible to have such a logic with handlebars or other templating languages? If they are not build for these purposes, please recommend me another way to solve this problem.
I am trying to do as follow:
Get a list of paired values - each value includes a name and a number
present the user with a list of buttons , each button shows the name from the name-value pair, so if I get 10 pairs, I will present 10 buttons
when the user clicks the chosen name, the button invokes a JS with the name-value matched.
I am very new to HTML , so this part is the problematic for me.
The page is not required to look nice at this stage, just function correctly.
<html>
<head> </head>
<body>
<script>
var pairs = [
{
"name_1": 123
},
{
"name_2": 983
},
{
"name_3": 567
}
];
function present_buttons(pairs) {
for (var i in pairs) {
console.log(`index = ${i}`);
console.log(`name = ${pair[i].name}`);
console.log(`value = ${pair[i].value}`);
// send info the the HTML section, so present proper names on buttons
// make sure to hook matching value for each button so it will be sent correctly to the use_value function later on
}
}
function use_value(value) {
// do something with the value triggered by the matching name button
}
</script>
<!--
get names to present on buttons from the present_buttons()
when a button is clicked , send the matching value to the use_value() function
-->
</body>
</html>
Try this:
<html>
<head></head>
<body>
<script>
var pairs = [
{ "name_1" : 123 } ,
{ "name_2" : 983 } ,
{ "name_3" : 567 }
];
for (var i = 0; i < pairs.length; i++) {
var button = document.createElement('button');
var pair = pairs[i];
button.innerHTML = Object.keys(pair)[0];
button.addEventListener('click', function (pair) {
use_value(pair);
}.bind(this, pair));
document.getElementsByTagName('body')[0].appendChild(button);
}
function use_value(value) {
// do something with the value triggered by the matching name button
}
</script>
</body>
</html>
I have JSON data and I guess my JSON is works but there is something that I didn't understand how it's going to work ? when I wrote cities or countries nothing happend how will I make it work ?
I havedata-list attribute and when I clicked my input my data-list opening automatically it's ok so far.but if I wrote something my inline data-list attribute musn't work anymore only my Json must work how can I do that ?
I'm using Awesomplete plugin and if you want to see my project on codepen please click to see on codepen
var myJSON = '{ "cities":[ "copenhagen", "london", "hamburg" ], "countries":[ "denmark", "norway", "sweden" ] }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = "Cities : " + myObj.cities;
document.getElementById("demo1").innerHTML = "countries : " + myObj.countries;
function showlist() {
}
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('#test').addEventListener("click", function() {
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
} else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
} else {
comboplete.close();
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet" />
<div id="demo"></div>
<div id="demo1"></div>
<!--<input type="text" class="awesomplete" data-list="PHP,ASP,ASP.NET,Python,CSS,HTML,C#,C++,Delphi,Visual Basic" onclick="showlist()">-->
<br><br> with auto list
<input id="test" data-list="CSS, JavaScript, HTML, SVG, ARIA, MathML" class="dropdown-input" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
You have to access the attribute "data-list" of your input and set your json as data source.
Try this:
var testInput = document.getElementById("test");
testInput.setAttribute("data-list", myObj.countries)
<!-- The select drop down menu (works fine) -->
<select id="select-event-type">
<?php foreach ($this->events as $event) {
echo "<option value='" .$event->event_id. "'>" .$event->event_title."</option>";
}?>
</select>
<!-- The javascript, which is supposed to output something according to the chosen option in the select drop down -->
<script>
(function ($) {
var events = <?php echo (count($this->events) > 0) ? json_encode($this->events) : "null"; ?>;
$(document).ready(function() {
$('#select-event-type').change(function() {
if (events) {
var event = events[this.selectedIndex];
$('#event-details').html(event);
}
});
});
})($);
</script>
<!-- In this div the output will be displayed -->
<div id="event-details"></div>
The event variable undefined.
If I for example do this: var event = 'hello' It does output 'hello' as it is supposed to.
So the problem seems to be with this part: events[this.selectedIndex];. What did I do wrong?
I am really new to this. Thank you so much for your help!!
UPDATE:
Console output (in chrome):
<script>
(function ($) {
var events = JSON.parse({"1":{"event_id":"1","event_title":"event1","event_desc":"event1","event_location":"eventlocation","event_requirements":"event1","event_date":"2022-07-20 15:00:00"},"2":{"event_id":"2","event_title":"event2","event_desc":"event2","event_location":"eventlocation","event_requirements":"event2","event_date":"2015-04-20 15:00:00"},"3":{"event_id":"3","event_title":"event3","event_desc":"event3","event_location":"eventlocation","event_requirements":"event3","event_date":"2019-11-20 16:00:00"}}); $(document).ready(function() {
$('#select-event-type').change(function() {
if (events) {
var event = events[$(this).selectedIndex];
$('#event-details').html(event);
}
});
});
</script>
JSON:
{
"1": {
"event_id": "1",
"event_title": "event1",
"event_desc": "event1",
"event_location": "eventlocation",
"event_requirements": "event1",
"event_date": "2022-07-20 15:00:00"
},
"2": {
"event_id": "2",
"event_title": "event2",
"event_desc": "event2",
"event_location": "eventlocation",
"event_requirements": "event2",
"event_date": "2015-04-20 15:00:00"
},
"3": {
"event_id": "3",
"event_title": "event3",
"event_desc": "event3",
"event_location": "eventlocation",
"event_requirements": "event3",
"event_date": "2019-11-20 16:00:00"
}
}
To get the value of the select element use this.value. Thus change:
var event = events[this.selectedIndex];
To:
var event = events[this.value];
However, if you json is an array with indices 0,1,2,3,4 rather than an object with option values as keys then your use of this.selectedIndex is correct.
UPDATE:
In the light of the sample JSON posted the correct code should be:
var event = events[this.selectedIndex + 1].event_title;
Special Note
You can get all the event data by using either:
var event = JSON.stringify( events[this.selectedIndex + 1] ); //gives you a string of everything
Or you could construct how you want it to look like so:
var event = $('<div/>');
$.each( events[this.selectedIndex + 1], function(k,v) {
event.append( $('<div/>',{text:k + ': ' + v}) );
});
See this answer for the jQuery way of accessing the selectedIndex property. Your answer might look like:
var event = events[$(this).prop("selectedIndex")];
Firstly you dont need the 2 ready instances. Try to do it, if dont work please tell me.
<script>
$(document).ready(function() {
var events = <?php echo (count($this->events) > 0) ? json_encode($this->events) : "null"; ?>;
$('#select-event-type').change(function() {
if (events) {
var event = events[$(this).selectedIndex];
$('#event-details').html(event);
}
});
});
</script>
and what means the selectedIndex ?
How to declare and initialize an array with key/values using JavaScript and then dynamically creating select dropdown and assigning key/values to the options using JavaScript?
Thanks
It would be easier if you use JQuery... This is how it would be done in basic Javascript.
<html>
<body>
<span id="selectContainer"></span>
</body>
<script type="text/javascript">
var selectItems = {
me: "Hari Gangadharan",
friend1: "Asif Aktar",
friend2: "Jay Thomas",
friend3: "John Abrams"
}
selectItems["newFriend"] = "Niel Goldman";
var selectContainer = document.getElementById("selectContainer");
var selectBox = document.createElement("SELECT");
selectBox.id = selectBox.name = "friendList";
selectContainer.appendChild(selectBox);
for (var key in selectItems) {
var value = selectItems[key];
var option = document.createElement("OPTION");
option.text = value;
option.value = key;
selectBox.options.add(option);
}
</script>
</html>
You're not looking for an array for this, you should use an object, for instance :
var list = {"some option": 1, "another option": 2, "etc": 3};
To therefore insert these to a dropdown you could append it to an existing option list by doing
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
Combined the code may look something like :
<script type="text/javascript">
var options = {"some option": 1, "another option": 2, "etc": 3};
window.onload = function() {
for(var optionText in options) {
var option = new Option(optionText, options[listText], true, false)
document.getElementById("listName").options.add(option)
}
}
</script>
<select id="listName">
</select>
I hope that helps, it should be more than enough for you to get started.
Edit : You should obviously note that doing window.onload and replacing it with a function like that may cause undesired effects if you have existing code, so either make use of your existing library's loaded functions etc