I am trying to make a simple multilanguage site!
I have 3 buttons for 3 languages, when I press one of them, I get the value of that button value with jQuery and store it in a variable named clicked and I want to get data from JSON like this: data.clicked.name
How can i get the value of clicked on data.clicked.name?
html file
<div id="container">
<input class="btnL" type="button" value="MK">
<input class="btnL" type="button" value="EN">
<input class="btnL" type="button" value="AL">
</div>
script
<script type="text/javascript">
$(document).ready(function () {
$(".btnL").click(function () {
var clicked = $(this).attr("value");
$.getJSON('language.json', function (data) {
console.log(data.clicked.name);
// ex. if the value of clicked variable is="EN"
// I want to get this console.log(data.EN.name)
});
});
});
</script>
language.json
{
"EN": {
"name": "Name",
"surname": "Surname"
},
"AL": {
"name": "Emri",
"surname": "Mbiemri"
},
"MK": {
"name": "Име",
"surname": "Презиме"
}
}
Use brackets
console.log(data[clicked].name);
Related
I saw this Question but here no approach shown.
"element": [
{
"value": "<button #click='changeTheme()' class='theme-link btn btn-light'>Default</button>",
"class": "text-success"
}
]
I have bind the JSON data with Vue Component like the below:
<p v-else v-html="element[0].value"></p>
Now, I am trying to call this method. But it's not firing!
methods: {
changeTheme() {
alert("Y");
}
}
Maybe separate the action from the button by putting it on the object on a different key, and calling it on click of the element:
"element": [
{
"value": "<button class='theme-link btn btn-light'>Default</button>",
"class": "text-success",
"action": function () {alert("Y")}
}
]
<p v-else v-html="element[0].value" #click="element[0].action"></p>
I am trying to dynamically create a list of applicants in my HTML. I have a list of applicant saved in JSON format that I am reading in. I have an HTML template of the applicant "tile" that I read in, populate and then append to the page for each applicant.
My template:
<div>
<div class="name"></div>
<div class="age"></div>
<div class="gender"></div>
<div class="email"><i class="fa fa-envelope"></i></div>
</div>
My JSON data:
{
"applicants" : [
{
"name" : "John Smith",
"email" : "email#gmail.com",
"gender" : "Male",
"age" : "22"
}
]
}
My jQuery:
$.get("applicants.json", function(json) {
json.applicants.forEach(function(applicant) {
var newApplicant = $(templates).find("#applicant").html();
$(newApplicant).find(".name").append(applicant.name);
$(newApplicant).find(".email").append(applicant.email);
$(newApplicant).find(".gender").append(applicant.gender);
$(newApplicant).find(".age").append(applicant.age);
$(newApplicant).appendTo(".applicant-list");
});
});
After running this code, I am just getting the template back without the JSON information.
I have tried placing a console.log() after appending applicant.name but there is still no change to newApplicant.
Something else I tried was console.log($(newApplicant).find(".name").append(applicant.name).html()); which showed me that the .name is being populated but those changes are not persisting.
Can anyone see what I am doing wrong?
Thanks.
I am not sure if forEach would be a right one. You can use jQuery's $.each function to loop in an array with this being referred as the current iterated object:
$.each(json.applicants, function () {
var newApplicant = $("body").find("#applicant > div").clone();
newApplicant.find(".name").append(this.name);
newApplicant.find(".email").append(this.email);
newApplicant.find(".gender").append(this.gender);
newApplicant.find(".age").append(this.age);
$(newApplicant).appendTo(".applicant-list");
});
Snippet
$(function () {
json = {
"applicants" : [
{
"name" : "Nicholas Robinson",
"email" : "ntrpilot#gmail.com",
"gender" : "Male",
"age" : "22"
}
]
};
$.each(json.applicants, function () {
var newApplicant = $("body").find("#applicant > div").clone();
newApplicant.find(".name").append(this.name);
newApplicant.find(".email").append(this.email);
newApplicant.find(".gender").append(this.gender);
newApplicant.find(".age").append(this.age);
$(newApplicant).appendTo(".applicant-list");
});
});
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="applicant">
<div>
<div class="name"></div>
<div class="age"></div>
<div class="gender"></div>
<div class="email"><i class="fa fa-envelope"></i></div>
</div>
</div>
<div class="applicant-list"></div>
In the question you omitted two HTML elements that instead you mention in the jQuery code, so according to the latter, and correct me if I'm wrong, the HTML should look like that
<div class="applicant-list">
<div class="applicant">
<div class="name"></div>
<div class="age"></div>
<div class="gender"></div>
<div class="email"><i class="fa fa-envelope"></i></div>
</div>
</div>
Then, in the jQuery you should either use your $.get() function and then parse or use instead $.getJSON()
$.getJSON("applicants.json", function(json) {
json.applicants.forEach(function(applicant) {
var newApplicant = $('body').find(".applicant").clone();
$(newApplicant).find(".name").append(applicant.name);
$(newApplicant).find(".email").append(applicant.email);
$(newApplicant).find(".gender").append(applicant.gender);
$(newApplicant).find(".age").append(applicant.age);
$(newApplicant).appendTo(".applicant-list");
});
});
Using ng-repeat I am creating bunch of forms with values in it. With each form there is also button to add rows to that particular form with new fields. Code is below
HTML:
<form name="{{form.name}}"
ng-repeat="form in forms">
<h2>{{form.name}}</h2>
<div ng-repeat="cont in form.contacts">
<input type="text" class="xdTextBox" ng-model="cont.ac"/>
<input type="text" class="xdTextBox" ng-model="cont.a_number"/>
<input type="text" class="xdTextBox" ng-model="cont.p_id"/>
</div>
<button ng-click="submit(form)">Submit</button>
<button ng-click="addFields(form)">Add</button>
<hr>
</form>
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.forms = [{
"name" : "form1", "ac": 251, "a_number": "7933", "p_id": 33
}, {
"name": "form2", "ac": 252, "a_number": "7933", "p_id": 4
}, {
"name": "form3", "ac": 253, "a_number": "7362", "p_id": 3
}];
$scope.addFields = function (form) {
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
$scope.submit = function(form){
console.log(form.contacts);
}
});
It is not working. Here is the plunker for it:
http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=preview
This is how it should be looking(Difference is data object received from db is little different than this previously asked question):
http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview
Please let me know where the problem is. Thanks
Your addFields method is the problem. Just add a case for when form.contacts is undefined and set it to empty array. Or make each form item start with a contacts key set to an empty array.
$scope.addFields = function (form) {
if(typeof form.contacts === 'undefined') {
form.contacts = [];
}
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
Works with that change in this fork of your plunk.
Angular also has a helper function for determining when something is undefined you might want to use though I do not know if it really makes any difference.
angular.isUndefined(form.contacts)
I am making a simple search code. I can't find error. The error message says Uncaught SyntaxError: Unexpected identifier on javascript line 40 (target=document.getElementById("outputPlace").
Do not look at the button, I have not added event listener to it yet.
I just want that when I press enter products are displayed.
HTML CODE
<html>
<head>
<title>Price List </title>
</head>
<body>
<h1> PRICELIST </h1>
<form id="formSearch">
<div>
<label for="searchBox"> Search products here: </label>
<input type="text" placeholder="Type text here to search product" id="searchBox">
</div>
<div id="buttons">
<button id="getAll"> GET ALL PRODUCTS</button>
</div>
</form>
<div id="outputPlace">
</div>
<script src="product.js"></script>
</body>
</html>
JAVASCRIPT CODE
(function(){ //start anonymous function
var list= {
"listOfProducts": [
{
"name":"hard disk",
"price": "50$",
"quality":"good",
},
{
"name":"monitor",
"price":"100$",
"quality": "very good",
},
{
"name":"speakers",
"price":"20$",
"quality": "not bad",
},
{
"name":"headphones",
"price":"12$",
"quality":"bad",
},
{
"name": "mobile phone",
"price": "300$",
"quality": "excellent",
},
{
"name": "usb memory",
"price": "30$",
"quality": "the best",
}
]
},
var target=document.getElementById("outputPlace"),
searchForm=document.getElementById("formSearch"),
productList=list.listOfProducts,
listLength=productList.length,
searchValue=document.getElementById("searchBox"),
searchInput=searchValue.value;
var listMethods = {
searchList: function(event) {
event.preventDefault();
var i;
target.innerHTML="";
if(listLength>0 && searchInput!=="") {
for(i=0;i<listLength;i++) {
var product=productList[i],
whatIsFound=product.name.indexOf(searchInput);
if(whatIsFound!==-1){
target.innerHTML+='<p>'+product.name+', '+product.price+', '+product.quality+'click here to buy</p>'
}
}
}
},
};
searchForm.addEventListener("submit",listMethods.searchList,false);
}) (); //end anonymous function
You have a comma after that large JSON object you defined at the top of your JavaScript, followed by another var.
var list= {
"listOfProducts": [
{
"name":"hard disk",
"price": "50$",
"quality":"good",
},
...[a bunch of stuff]...
},
var target=document.getElementById("outputPlace"),
searchForm=document.getElementById("formSearch"),
productList=list.listOfProducts,
listLength=productList.length,
searchValue=document.getElementById("searchBox"),
searchInput=searchValue.value;
Both of the two other proposed answers would fix this (well ok Otome deleted their answer which was to drop the second var).
Change this
var list = {
...
},
var target=document.getElementById("outputPlace"),
to this:
var list = {
...
};
var target=document.getElementById("outputPlace"),
And you have one more comma at the end of script, after }
I'm dealing with pretty big amounts of json and the data is something like this:
{
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7,
"field": {
"field": "value"
}
}
]
}
Whenever I change anything I get a new response which is somewhat similar to the previous data, but where new properties might have been added, stuff might have been removed and so on.
My testcode is something like this (don't mind the infinite amount of bad practices here):
<div data-viewmodel="whatevz">
<span data-bind="text: stuff['nested-thingy']"></span>
</div>
<script>
function vm() {
var self = this;
this.stuff = ko.observable();
require(["shop/app"], function (shop) {
setTimeout(function () {
self.stuff(shop.stuff);
}, 1200);
});
}
ko.applyBindings(new vm(), $("[data-viewmodel]")[0]);
</script>
I want stuff['nested-thingy'] to be updated whenever stuff is updated. How do I do this without all kinds of mapping and making everything observable?
You should only have to update your biding:
<div data-viewmodel="whatevz">
<span data-bind="text: stuff()['nested-thingy']"></span>
</div>
You have to access the value of the observable with the (). That returns your object and then you can access it. The content of the binding is still dependent on the observable stuff therefore it should update whenever stuff is updated.
At least my fiddle is working that way: http://jsfiddle.net/delixfe/guM4X/
<div data-bind="if: stuff()">
<span data-bind="text: stuff()['nested-thingy']"></span>
</div>
<button data-bind="click: add1">1</button>
<button data-bind="click: add2">2</button>
Note the data-bind="if: stuff(). That is necessary if your stuff's content is empty at binding time or later...
function Vm() {
var self = this;
self.stuff = ko.observable();
self.add1 = function () {
self.stuff({'nested-thingy': "1"});
};
self.add2 = function () {
self.stuff({'nested-thingy': "2"});
};
}
ko.applyBindings(new Vm());
Any reason you can't use the mapping plugin to deal with the mapping for you? You can use the copy option for the properties that you don't want to be made observables:
var mapping = {
'copy': ["propertyToCopy"]
}
var viewModel = ko.mapping.fromJS(data, mapping);