How reload the helper once i change the values - javascript

Im trying to filter information in my page after the user select an option, so i made a "change" event and passed values ​​through the helper by sessions and its ok console log looks like the values passed ok, but it seems like the helper doesn't refresh or something because dont return the find with the new values, actually don't do anything, obviously there is something wrong, sorry for my ultra basic english, i hope you understand and help me, thanks for your time!
Template
<select id="mostrarTiposMenu" class="form-control">
{{#each mostrarMenus}}
<option value="{{nuevoTipoMenu}}" onchange="getMenu()">{{nuevoTipoMenu}}</option>
{{/each}}
</select>
Events and helpers
Template.main.events({
"change #mostrarTiposMenu": function(evt) {
var newValue = $(evt.target).val();
Session.set("valueMenu", newValue);
console.log("yo estoy en el event " + newValue);
}
});
Template.main.helpers({
mostrarMenus : function(){
return Menu.find();
},
mostrarPrimerDia: function(){
var searchMenu = Session.get("valueMenu")
console.log("Yo estoy en el helper " + searchMenu)
var server = TimeSync.serverTime()
var diaDeHoy = moment(server).locale("es").add(0,'days').format('dddd');
return Promociones.find({'metadata.diaOferta' : { $in: [diaDeHoy] } },{'metadata.tipoMenu' : { $in: [searchMenu] } });
}
});

did you tried using refresh option
$('selectmenu).refresh();

Related

Where do I put this function in my code? jQuery

Okay, so for class I have to make a CRUD application basically. I have to have a nav bar that links to different "pages" that are loaded in using a server.js file. In that server is where I load a JSON file that holds two arrays, one for pages, or sections, and another for users. The goal is to input information about a user in one section, hit a button and then that user's info will be listed in a different section. You also need to be able to delete each individual user at will, and it's all local.
My problem is that I have this addUser function, and within this function there's a click listener for the add button. Right now, the only thing it does when it's supposed to be clicked it throws a console.log, but I can't get that to work. The addUser function also has a console.log that's running fine, and I believe that my problem is that I don't know where I'm supposed to be adding the addUser function into my code. Just to be safe, I'll go ahead and list all my code. First is the server.js:
var SERVER = (function(){
//variable to store data.users into
var _userData = [];
var _sectionData = [];
//getting the data and putting it into the variables above
var _loadData = function(){
$.getJSON("./data/data.json", function(data){
_userData = data.Users;
_sectionData = data.Sections;
//console.log(_sectionData);
})
}
var _showData = function(){
return _userData;
}
var _getSection = function(sectionYouWant){
let sec = {};
$.each(_sectionData, function(idx, section){
if(section.sectionName == sectionYouWant){
sec = section.sectionContent;
}
});
return sec;
}
_loadData();
return {
loadData: _loadData,
showData: _showData,
getSection: _getSection
}
})()
next is the app.js
function addUser(){
console.log("firing addUser");
$('#addButton').click(function(e){
console.log("are you working????")
e.preventDefault();
})
}
function initNavListeners(){
$("#home").click(function(e){
//console.log('click home');
var sectionData = SERVER.getSection('home');
$('.wrapper').html(sectionData);
});
$("#view").click(function(){
//console.log('click view users');
var userData = SERVER.showData();
var sectionData = SERVER.getSection('view');
$(".wrapper").html(sectionData);
function showUsers(){
$.each(userData, function(idx, user){
$(".wrapper").append(`
<br/><p><b>Name:</b> ${user.fName} ${user.lName}</p>
<p><b>Email Address:</b>
${user.email}</p>
<p><b>Twitter Handle:</b>
${user.twitter}</p>
<button class="delete" id=${idx}>DELETE</button><br/>`)
})
}
showUsers();
});
$("#register").click(function(e){
//console.log('click register');
addUser();
var sectionData = SERVER.getSection('register');
$('.wrapper').html(sectionData);
});
}
$(document).ready(function(){
SERVER.loadData();
initNavListeners();
var sectionData = SERVER.getSection('home');
$('.wrapper').html(sectionData);
})
Finally, the JSON:
{
"Users": [
{
"fName": "Andrea",
"lName": "Trigg",
"email": "at#users.com",
"twitter": "#at"
}
],
"Sections": [
{
"sectionName": "home",
"sectionContent": "<h1>HOME</h1><p>Welcome to the home page for my Homework 5 assignment! In this little application, you can register users and it will be submitted to a local JSON file. Then when you go to the view users page, it will show all the current users registered. You can also delete each individual user by pressing the \"delete user\" button below their information.</p><p>I hope this will work on your machine because it definitely works on mine!</p><p>I'm honestly not sure what else I should put here, so have a gif of a cute kitten trying to eat their own tail.</p><img src=\"https://i.pinimg.com/originals/84/c8/ba/84c8bab01787f2ee1ebef1378e9e8444.gif\"><p>I hope you have a great week! Thank you for taking a look at my Homework 5!</p>"
},
{
"sectionName": "view",
"sectionContent": "<h1>VIEW USERS</h1><p>Scroll below to see all users stored in the database. Click the delete button to delete a user from the database (careful, you won't get the information back if you delete!)</p>"
},
{
"sectionName": "register",
"sectionContent": "<h1>REGISTER</h1><p>Register a new user by using the form below!</p><form><input id=\"first\" type=\"text\" value=\"\" placeholder=\"First Name:\"><br/><input id=\"last\" type=\"text\" value=\"\" placeholder=\"Last Name:\"><br/><input id=\"emailAddress\" type=\"text\" value=\"\" placeholder=\"Email:\"><br/><input id=\"twitterHandle\" type=\"text\" value=\"\" placeholder=\"Twitter Handle\"><br/><input id=\"addButton\" type=\"button\" value=\"SUBMIT\"></form>"
}
]
}
If you see anything that could be causing my click listener to not be working while the function itself is, that would be a tremendous help. I'm really struggling with this so any help would be great! Thank you!
Wow okay so after working on this for three hours, I finally figured it out.
So basically, you take the addUser function and instead of having it be global, you put it into the #register click listener that's in the initNavListener. It should look something like this:
$("#register").click(function(e){
//initListeners();
//console.log('click register');
var userData = SERVER.showData();
var sectionData = SERVER.getSection('register');
$('.wrapper').html(sectionData);
function addUser(){
console.log("firing addUser");
$('#addButton').click(function(e){
console.log("are you working????")
e.preventDefault(); )}
I feel like the biggest idiot right now :'D
ETA: If anyone wants to help me figure out how to delete these users that would be cool, but it's not listed in the rubric as something that I need to do, so I'm not putting major emphasis on it atm.

oj-select-one show undefined for all options

i have an observable array that get its values from REST
$.getJSON(rootModel.soho()).
then(function (StudentCourseView1) {
$.each(StudentCourseView1.items, function () {
self.data.push({
StudentId: this.StudentId,
CourseId: this.CourseId,
Enrollmentdate :this.Enrollmentdate,
Notes :this.Notes,
Id : this.Id,
CourseName : this.CourseName,
StudentName: this.StudentName
});
});
});
self.dataSource = new oj.ArrayTableDataSource(
self.data,
{idAttribute: 'Id'}
);
and i have created select-one like this
<oj-select-one id="select1" style="max-width:20em"
options={{data}}
value="{{data.Id}}"
options-keys="[[data.StudentName]]" >
</oj-select-one>
the select one show undefined for all it options
Are you sure the ajax call is working, and there are no errors in console? Is the drop-down showing a list of blank values?
If yes, then the only missing element is adding option-keys attribute, to explain what data to show the user, and the key for each piece of data.
<oj-select-one id="select1" style="max-width:20em"
options={{data}}
options-keys="{{optionKeys}}"
value="{{StudentId}}">
JS
//You can change this acc. to your convenience.
self.optionKeys = {value:"Id", label:"StudentName"};

$.getJson won't affect view until event

Didn't really know how to word the question. Using angular. Anyways, I'm trying to have it so when the user types in the text box a state, once it has been verified that the state exists (comparing to an array of all 50), it will automatically call a getJSon Jquery request for a JSON object. But for some reason, it doesn't execute right away, instead I have to press a key after doing so.
Code:
$scope.checkState = function(team) {
//check for team
console.log("Searching for " + document.getElementById('team').value)
var teamFind = document.getElementById('team').value;
var team = $.inArray(teamFind, $scope.states);
console.log("team: " + team);
if (team == -1)
{
console.log("Not found");
$scope.selectedState = "Not Found";
teamFound = false;
}
//correct team
if (team > -1)
{
$.getJSON('https://api.myjson.com/bins/1ak21r', function (data) {
//console.log(data.bowl);
$scope.items = data;
console.log($scope.items);
console.log("Team Bowl: " + team_bowl)
console.log("Found: " + $scope.states[team]);
$scope.selectedState = $scope.states[team];
teamFound = true;
});
}
}
html code
<p class="w3-large w3-center">
<input type="text" name="team" id="team" value="Whats Your Team?" ng-keyup="checkState(team)">
</p>
<p class="w3-jumbo w3-center">
<span id="bowl">{{ selectedState }}</span>
</p>
<p class="w3-large w3-center">
<span>f{{ items }}</span>
</p>
</div>
I know it might be hard to understand what I want, but I was creating a sample application that would show what bowl game a team was competing in. The user types the team into the text-box id=team below, and I wanted it done without them having to press enter or submit.
On the key-up, it runs the check function. So for example, once Maryland is entered, the getJson will run and correctly logs the data, but the $scope.items isn't updated until after I type one more key AFTER I entered the state
So like typing:
M-A-R-Y-L-A-N-D(CONSOLE LOGS THE JSON OBJECT CORRECTLY, BUT ON THE HTML {{ items }} STILL SHOWS NOTHING)-any_key_here(NOW IT GETS UPDATED)
Thanks for any help.
EDIT:
So I was able to get it by having another function be called with the data inside the JSON function.
myFunction(data);
which calls
function myFunction(items) {
console.log(items);
document.getElementById('bowl2').innerHTML = items.team;
};
You are using jQuery's ajax method which does not integrate with angular to inform angular when it is done. It's best to use angular's built in $http methods which do the same thing expect when they complete they trigger a digest cycle which will update the view.
You will need to inject $http into your controller or service (depending on where this code lives) in order to use it. Once you do that, you should be able to make the following modification to you code.
Change
$.getJSON('https://api.myjson.com/bins/1ak21r', function (data) {
//console.log(data.bowl);
$scope.items = data;
console.log($scope.items);
console.log("Team Bowl: " + team_bowl)
console.log("Found: " + $scope.states[team]);
$scope.selectedState = $scope.states[team];
teamFound = true;
});
to
$http.get('https://api.myjson.com/bins/1ak21r')
.then(function (response) {
var data = response.data;
//console.log(data.bowl);
$scope.items = data;
console.log($scope.items);
console.log("Team Bowl: " + team_bowl)
console.log("Found: " + $scope.states[team]);
$scope.selectedState = $scope.states[team];
teamFound = true;
});

Value in object returns to empty

I'm using a select form with data retrieved from a JSON url. When I select something, I want the value to be put into $scope.afspraak.groep. For some reason, the value returns to the original value which is empty.
Here is my code:
<select id="selectgroep" name="selectgroep" class="form-control" size='5' ng-model="afspraak.groep" ng-options="t.id as t.id for t in objecten" ng-click="test()">
</select>
$scope.afspraak = {
groep: '',
};
$scope.passData = function(data) {
$scope.afspraak.groep = data;
}
$scope.test = function() {
console.log($scope.afspraak);
}
I have used various methods such as changing ng-click to passData(afspraak.groep), but it still doesn't work. The weird thing is that in another partial, I have the exact similar code and that does work shown here:
<select id="selectvak" name="selectvak" class="form-control" size='5' ng-model="user.vakid" ng-options="t.id as t.id for t in vak" ng-click="getKlas(user.vakid); test()">
</select>
$scope.user = {
vakid: '',
};
$scope.test = function() {
console.log($scope.user);
}
$scope.getKlas = function (ID){
afsprakenService.getKlassen(ID)
.success(function (klas){
$scope.klas = klas;
$scope.alerts.push({ type: 'success', msg: 'Retrieved'});
})
.error(function (error) {
$scope.alerts.push({ type: 'danger', msg: 'Error retrieving! ' + error.message});
});
};
What am I doing wrong here? The only difference that I see is the method in the second select form which is getKlas where I pass the ng-model to use in another function.
Edit: this is now solved! It turns out that a label class is what was causing the deletion. I removed it by accident and it works now!
To set a models value from a select it is sufficient to have a ng-model on it. In case you want to do some extra action when selecting an option you should use ng-change and not ng-click.
A good way to debug your models, to check in real time if it was updated and view its values do something like this
<pre>{{ myModel | json }}</pre>
Here is a working fiddle example: http://jsfiddle.net/jub58sem/2/

Adding more, another loop to my Underscore template with a new backbone model?

UPDATE :
I have got my code working, of sorts, but I have two issues and one problem I am not sure how to fix. I will post my current code below. One The Clients append to the right section within the TimesheetData template. But it wraps the option tag within the ClientData template within another option .
So I get :
<select>
<option> <option value="XX"> XXX </option> </option>
</select>
Now I know this is what it is designed to do, to have a root element but I can not seem to find a solution to this issue, although it still works.
Now the other issue is that I need to select a default client, which is loaded into the Timesheet model, Timesheetrow.client_id holds what the database as saved for that row. I just not sure how to access this in an if statement or some other way within the client template.
Now the problem I have is that the Client data does not always load? So when I reload / refresh the page it sometimes lists all my clients in option tags, sometimes it loads nothing, just giving me an empty select tag. However when it does not load anything, I don't have any console log errors or anything?
All help most welcome :)
So this is my current Backbone code:
Client Data Code :
var ClientModel = Backbone.Model.extend({
defaults: {
Client: "",
}
}); //End of ClientModel
var ClientCollection = Backbone.Collection.extend({
model: ClientModel,
url: '/dashboard/json/clients'
}); //End of ClientCollection
var ClientView = Backbone.View.extend({
tagName: 'option',
template: _.template($('#ClientData').html()),
render: function() {
this.$el.append(this.template(this.model.toJSON()));
return this.$el;
}
});
Timesheet Data Code :
var TimeSheetModel = Backbone.Model.extend({
defaults: {
Timesheetrow: "",
}
}); //End of TimeSheetModel
var TimeSheetCollection = Backbone.Collection.extend({
model: TimeSheetModel,
url: '/dashboard/json/row/' + TimesheetID()
}); //End of TimeSheetCollection
var TimeSheetRowView = Backbone.View.extend({
className: 'TimesheetRowLine',
template: _.template($('#TimesheetData').html()),
render: function() {
this.$el.append(this.template(this.model.toJSON()));
return this.$el;
}
}); //End of TimeSheetRowView
Timesheet & Client Code Section:
var TimeSheetCollectionView = Backbone.View.extend({
el:'#MasterContainer',
template: _.template($('#TimesheetForm').html()),
events: {
"click .actionSubmit": "handleSubmit"
},
initialize: function() {
//Get Client Data & Add To Template
this.clientcollection = new ClientCollection();
this.listenTo(this.clientcollection, "add", this.AddClient);
this.clientcollection.fetch();
//Get Main Timesheet Data & Add To Template
this.collection = new TimeSheetCollection();
this.listenTo(this.collection, "add", this.AddTimesheetRow);
this.collection.fetch();
this.$el.append(this.template());
this.submitButton = this.$(".actionSubmit");
},
AddTimesheetRow: function(model) {
var view = new TimeSheetRowView({model: model});
view.render().insertBefore(this.submitButton);
},
AddClient: function(model) {
var clients = new ClientView({model: model});
$("#TimesheetDataList .TimesheetRowLine #clienttemp").append( clients.render() );
},
handleSubmit: function(){
//in real life, you would validate and save some model
alert("form submit");
return false;
}
}); //End of TimeSheetCollectionView
var collectionView = new TimeSheetCollectionView();
This is my Underscore Template code:
<script type="text/template" id="TimesheetForm">
<form action="#" method="post" id="TimesheetDataList" style="width: auto; padding-left: 50px;">
<input type="submit" class="actionSubmit" value="Send"/>
</form>
</script>
<script type="text/template" id="TimesheetData">
<%= console.log( Timesheetrow.client_id ) %>
<input type="hidden" name="data[Timesheetrow][<%= Timesheetrow.id %>][id]" value="<%= Timesheetrow.id %>">
<input type="type" name="data[Timesheetrow][<%= Timesheetrow.id %>][jobtitle]" value="<%= Timesheetrow.twistjob %>">
<select name="data[Timesheetrow][<%= Timesheetrow.id %>][client_id]" id="clienttemp"></select>
</script>
<script type="text/template" id="ClientData">
<option value="<%= Client.id %>"><%= Client.clientname %></option>
</script>
OLD POST
Ok, I am having an issue with my Backbone view rendering into my Underscore template, again. I thought it would be best to ask it as a new question.
My last question, Underscore Template Looping, Without A Loop?, the guy on there help me very well but I am now trying, with little success to edit this code and extend it a little more.
CODE REMOVE - SEE UPDATE
So I was trying to follow the same methods. I know I have to look up more training to expand my knowledge.
With this code, I have a list of clients, I need to load into a select / option pull down form element. But it only seems to loop around 17 times, which is the number of rows I have in my timesheet. I am console logging 'Client' in the 'ClientData' template, this is what displays my client data but only the client data that is logged in my timesheet rows, not all the clients from the JSON data that the model / collection is pointing to? I am also getting a ref. Error for Client? Even though it is in my model as a default?
I am understanding backbone (a bit), but not Underscore so much.
All help most welcome.
Thanks,
:: EDIT ::
I thought I would post my Underscore templates.
CODE REMOVED - SEE UPDATE
So what I am trying to do is loop around in ClientData template for all the clients, with 'option' tags, then add this to the select elements on the TimesheetData template. Then it is complete by this template being added to the TimesheetForm template, which it already does.
This might need a different method and might have been my fault that it don't work as I forgot to explain on the other question a out my client list.
Thanks,

Categories

Resources