I want to know abt DOM manipulation in meteor. My code goes as follows:
<template name = "studentList">
{{#each}}
<div class = "name">
Name: {{this.name}}
</div>
<div class = "age">
Age: {{this.age}}
</div>
<button class = "edit"> Edit </button>
{{/each}}
<button class = "addStudent"> Add Student </button>
</template>
Template.studentList.helpers({
studentlist:function(){
return Students.find();
}
});
Template.studentList.events({
//I am doing the DOM manupulation here based on the buttons clicked
});
I get a list of Student Info from the DB and display them in the template. Now for each student, there is an edit button. When user clicks this edit button, I want to change the "name" and "age" field of the student as text field and give an option to "save" and "cancel".
Similarly, I have an "add student" button at the end of the template. When a user clicks it, I want to display a form, where student's name and age is added and then saved.
So far, I am being able to do this, but in a very naive way by using lots of Jquery/Javascript code in the events of studentList. I read many post that says this is not the correct way.
Can anyway please tell how can this feature be achieved in meteor. Or just to some possible ways of doing it.
Help appreciated.
This is a possible way to accomplish this.
Lets try to do this step-by-step
First this is how the HTML should look.
{{#if editName}} <!-- editName template helper -->
<!-- If the Session is equal to true this part of the html will be showed -->
<input type="text" class="newName" value="{{this.name}}" />
{{else}}
<!-- this is what we show by default on the view, if user click the div, the input will be showed -->
<div class="name">Name: {{this.name}} </div>
{{/if}}
Now the JS.
The helper should look like this.
Template.studentList.helpers({tName:function(){
return Session.get("studentName" + this._id); //getting the session true or false.
}
});
And the Events.
Template.studentList.events({
'click .name' : function(event,template){
//On this event we are Setting the Session to true and holding the id of the student
return Session.set("studentName" + this._id,true)
},
'keypress .newName':function(event,template){
//Some keypress to update the value
//using http://docs.meteor.com/#/full/template_$ to get the value using meteor
var newNameStudent = template.$('.newName').val();
if(event.keyCode == 13){ //if enter lets update the value
Students.update({_id:this._id},{$set:{name:newNameStudent}})
return Session.set("studentName" + this._id,false) //setting to false the session to hide the input and show the <div>
}
},
'click .cancel':function(){
return Session.set("studentName" + this._id,false) //setting to false the session to hide the input and show the <div>
}
})
If you see there is not too much code (i guess), you get the idea how to use the sessions to do simple CRUD operations.
I made a Meteorpad of this working example, check it.
Related
I'm Junior Django dev. It's my first project in my company and I have a FrontEnd task.
The frontend is black magic for me but trying my best but here I am totally lost;/
Task to do:
"If I click on checkbox it redirect to page with an endpoint which change
value of checkbox from on to off"
I wrote all backend staff... and even some kind of frontend but it is not working as I want it to. I've tried loads of combination but I still don't know.
Code of checkbox:
<table>
<thead>...</thead>
<tbody>
<td>
<a href="{% url 'product_user_paid_change' tp_id=item.pk paid=item.paid %}" onclick="return confirm('For surechange - {{ item.full_name }}?')">
<div class="checkbox m-15">
<label for="id_paid"><input type="checkbox"{% if item.paid == True %} checked{% endif %} ><i class="input-helper"></i></label>
</div>
</a>
</td>
</tbody>
</table>
And what is happening here?
When I click directly on checkbox there appears a confirmbox when I
click "OK", checkbox change state but request is not send...
When I click outside checkbox there is confirmbox and when I click "OK" I'm correctly redirected to request site.
How to make it work when I click directly on checkbox... not only outside? ;/
I tried to transport this before div, after div, before label, inside label... nothing works.
I will appreciate any help!
Its pretty simple, and as my edit dont have nothing to do with python or django.
What you have to do it create one input checkbox at your template
<input type="checkbox" id="my_awesome_checkbox">
Create one javascript function or just bind the code to event in that input
<input type="checkbox" id="my_awesome_checkbox" onchange="myCuteFunction">
function myCuteFunction() {
var checkBox = document.getElementById("my_awesome_checkbox")
if (checkBox.checked == true){
let result = confirm("Hey! You really want to leave me here?");
if (result){
location.replace("the url you wan to go");
}
}
}
EDIT: You want to changed the Checkbox value based on information from your backend?
If is that you can use ajax to get the response you want from your endpoint and change your checkbox
So using the previous code you can call the ajax to reach your backend instead of changing the page your url... and than change the value of your checkbox
function myCuteFunction() {
var checkBox = document.getElementById("my_awesome_checkbox")
if (checkBox.checked == true){
let result = confirm("Hey! You really want to leave me here?");
if (result){
$.ajax({
url: "<your endpoint>",
context: <necessary paramenters>
}).done(function() {
<your response to add your logic to change the checkbox>
});
}
}
}
Hello everyone and sorry in advance for my very bad English.
I'm working on an ASP.NET MVC project with a JavaScript framework as the front-end.
I have a table which contains customer names retrieved from a database. Now I want to show a modal dialog and set the text of its header according to the customer name which has been clicked. At the same time I would like to get the customer Id. For example, when clicking "Georges", the modal dialog pops up and its header text is set to "Georges".
Here is my code.
The customer table look like this:
<div class="col-lg-6">
<div class="container-fluid" id="DailyTask">
<h4>Daily Tasks</h4>
#if (Model != null)
{
List<SchedulerTool.Models.spGetDailyBatchTask_Result> batches = Model.DailyTask;
foreach (var batch in batches)
{
<div class="bs-callout bs-callout-warning" id="dailybatch">
<input name="currentdailyBatchId" id="#batch.BatchId" hidden type="text" value="#batch.BatchId" />
<input name="currentdailyBatchName" id=" #batch.BatchName " hidden type="text" value=#batch.BatchName />
<button class="btn btn-group-justified" id="dailybatchTask" data-title="#batch.BatchName" data-target="#dailybatchTaskModal" data-toggle="modal" data-bid="#batch.BatchId">
<span class="fa-bitbucket-square" id="name">#batch.BatchName</span>
</button>
</div>
}
}
</div>
The JavaScript code is:
$('dailybatchTask').on('click', function ()
{
var batchId = $(this).data('bid');
var batchName = $(this).data('title');
// Here I set the table name a template table
$("h4 a#bathDailyTaskModalLabel").html(batchName);
// Here I set the Id to a template table
loadMasterTable("LoadObjectsNotBatched", batchId, DailyBatchElementUrl, "DailyBatchCollapseElementId");
});
Customers table:
The modal that is popover when clicked on customer:
The problem is: when I clicked on the first element of the customer table, the modal is correctly shown (the header and id are correct) but when I clicked on the others elements the JavaScript code is not executed.
Hope someone can try to understand my problem and will help me!
You are trying to catch all buttons by ids. But in HTML ids must be unique. Because that jquery your click event only matches first data. You need to fix ids before jquery part. If you really need it you can define a counter for loop and use it like this;
id="dailybatchTask-#counter"
But you already defined data-bid so basically, you can just add a class name for the button like this;
class="btn btn-group-justified daily-batch-button"
then only you need to;
$('daily-batch-button').on('click', function () {
...
...
...
});
I am working on a site that has been written using AngularJS. On one of the pages, there is a button that opens up a 'Page Properties' dialog, that allows the user to change some of the properties of the page that they are currently viewing.
I want to add a checkbox to that dialog, which, when checked will set the current page as the Home page/ default page for the site (i.e. when the user clicks the site logo, or the 'Home' breadcrumb on any given page, it should then take them to the page on which they checked the 'Set as homepage' checkbox, rather than the default home page.
I have added the checkbox to the dialog, and am now just testing it, to see that I can capture whether or not it has been checked correctly, before I actually write the function to actually set the Home page to the user's choice, rather than the default.
The Angular markup for the dialog box is:
<form class="modal-body" role="form" data-ng-submit="confirm($event)" novalidate>
...
<div data-ng-show="layout.style === 'grid'">
...
<div class="divider"></div>
<div class="row checkbox">
<label class="col-sm-2" data-i18n="Homepage:"></label>
<div class="col-sm-10 checkbox">
<label class="checkbox">
<input name="homepageCheckbox" type="checkbox"
ng-click="layout.direction='row'"
ng-clicked="layout.direction==='row'">
<span data-18n="Set this page as the home page"></span>
</label>
</div>
</div>
...
This markup displays the checkbox correctly- when I click the button to open the dialog box, I can see that the checkbox I've added is displayed with it's label and text alongside it, & I am able to select/ deselect it.
I am now starting to look into writing the JS required to actually change the home page to the selected page when the checkbox is selected, and thought I would start doing this by simply making sure I am correctly capturing whether or not the checkbox is selected.
To do this, I have located the JS function that is handling the dialog box, and added a few console.log() lines to it, to try and display the value of the checkbox at a given time:
.controller('PageLayoutPickerCtrl', function($scope, $route, $location, $timeout, Page, umConf, NotifyMgr, DialogMgr) {
if($scope.homepageCheckbox == 'true'){
console.log("homepageCheckbox is selected");
} else {
console.log("hompageCheckbox is not selected");
}
...
$scope.confirm = function(e) {
...
if($scope.homepageCheckbox == 'true') {
console.log("homepageCheckbox is selected inside $scope.confirm() = function()");
} else {
console.log("hompageCheckbox is not selected inside $scope.confirm() = function()");
}
};
...
})
So, due to where I've placed the console.log() statements, when the button is clicked to display the dialog, a statement should be shown in the console stating whether or not the checkbox is selected as soon as the dialog opens, and another statement should be shown in the console stating whether or not the checkbox is selected as soon as the 'Confirm' button is pressed on the dialog box.
At the moment, both of these console.log() statements are showing that the checkbox is not selected, regardless of whether I have actually selected it or not.
How can I capture the value of the checkbox correctly, so that when it is selected, and the user clicks the 'Confirm' button, I can change the Home page of the website to the current page?
You should use ng-model in your checkbox like this:
html
...
<label class="checkbox">
<input name="homepageCheckbox" type="checkbox"
ng-model="checkBoxModel"
ng-click="layout.direction='row'"
>
<span data-18n="Set this page as the home page"></span>
</label>
...
js
...
$scope.confirm = function(e) {
...
if($scope.checkBoxModel) {
console.log("homepageCheckbox is selected inside $scope.confirm() = function()");
} else {
console.log("hompageCheckbox is not selected inside $scope.confirm() = function()");
}
};
...
<input name="homepageCheckbox" type="checkbox" ng-model="homepageCheckbox"
ng-click="layout.direction='row'"
ng-clicked="layout.direction==='row'">
put ng-model="homepageCheckbox" and you are good to go, then in your controller,
check this:
if($scope.homepageCheckbox){
console.log("Checkbox is selected");
}
else{
console.log("Checkbox is not selected");
}
I have a view that gets data from Model and displays the information. I am getting a list of school with school name and school Id from Model and then using foreach loop, I am creating a dynamic table based the number of schools the Model returns.
Below is the code I have for my view.
#if (Model.SelectedSchool != null)
{
foreach (var sch in Model.SelectedSchool )
{
<table class="table-bordered">
<tr>
<td class="col-sm-9">
#sch.SchoolName
</td>
<td class="col-sm-3">
<button class="btn btn-default" id="recentlySelected" name="btnRecentlySelected" type="button">
Select
</button>
</td>
</tr>
</table>
}
}
Here SchoolName is the property in the list I am getting from Model.
SchoolId is also in the list.
Below is the view I get
Now, I want that when a user clicks Select button, beside each school name, that specific SchoolId, is passed to the .js file where I am handing the javascript functions and based on the schoolId, the javascript function, generates the address of the school.
My question is how can I link the SchoolId's that I am getting in the SelectedSchool list to the respective Select buttons.
Thanks in advance!
First of all, you are setting the same id to all the buttons generated from the loop. This is invalid HTML ! Id values should be unique. So delete the Id property (unless you absolutely need it for something. in that case you need to make it unique)!
You can keep the school id in html 5 data attribute and read it later in javascript as needed.
Assuming you have a property called SchoolId,
<button class="btn btn-default" data-schoolid="#sch.SchoolId"
name="btnRecentlySelected" type="button">
Select
</button>
You can have the same attribute value for name property. You can use this as your jQuery selector when registering the click event on these buttons.
Now some unobutrusive javascript to bind a click event on this button
$(function(){
$("[name='btnRecentlySelected']").click(function(e){
e.preventDefault();
var schoolId= $(this).data("schoolid");
alert(schoolId);
// to do : Do something with the schoolId
});
});
I am working on asp.net mvc3 application, in this i have user profile section this having many sections like general details, education, work and many...
Now my issue is i want user to insert their information and on click of add i want to display inserted information in another section and on click of save i want to insert all information into database.
Like,
Education Section::
In this user can fill their school details, college details.
School
School Division: Dropdown
School Name: Textbox
School Branch: Textbox
School Year: Dropdown
***Add School***
College
College Division: Dropdown
CollegeName: Textbox
CollegeBranch: Textbox
CollegeYear: Dropdown
***Add College***
**SAVE CANCEL**
I have this in my education section,
when user click on add school i want entered data display into another section and when user click on save button all data should go into database, so that we can reduce database roundtrip fo saving details on 1 click.
User can enter multiple schools and colleges in their profile.
My question is,
how can i display entered data into another section/div?
what is the best way to do this thing so that when user click on save button my code will fetch all entered data and saving data into database?
I tried this to display information entered on add school click but in this i am not able to get details back for saving.
function addSchool() {
var result = document.getElementById('schoolDiv').innerHTML + "</br>" + "<br/>School: " + document.getElementById('schooldiv').value + "<br/>School Name: " + document.getElementById('schoolname').value +"<br/>Branch: " + document.getElementById('branch').value + "<br/>School Year: " + document.getElementById('schoolyear').value;
document.getElementById('schoolDiv').innerHTML = result;
}
What is the best way to do so in asp.net mvc3?
It seems that you have only one problem, which is to extract the values already entered and display them in another format, almost like a running summary.
Firstly, I would highly recommend that you use a JavaScript library such as jQuery, which will take out all the heavy lifting of extracting and redisplaying values. You could also use the jQuery UI tabs plugin to handle the sections problem: http://jqueryui.com/demos/tabs/
Writing it yourself, there are various approaches you could take to redisplaying the entered data. One simple approach would be to have a Summary template, with its own sections, for example:
<div id="summary">
<div id="personalSummary" style="display: none;">
<p>Various elements to hold summary</p>
</div>
<div id="educationSummary" style="display: none;">
<p>Various elements to hold summary</p>
</div>
</div>
<form>
<div id='sections'>
<div id="personal">
<input type="button" value="Next" />
</div>
<div id="education" style="display: none;">
<input type="button" value="Next" />
</div>
</div>
</form>
So what you need now is some JavaScript that when they click on each button it extracts the values for that section and plugs them into the summary section and displays it. I can't show you how to do all of that but using the jQuery val function it would be something like:
<script type="text/javascript">
function completeSection(sectionId) {
var section = $('#' + sectionId);
var summary = $('#' + sectionId + 'Summary');
// swap a value over.
var value = $('#firstName', section).val();
$('#firstNameSummary', summary).val(value);
// etc
// now hide the input section, display the summary section and move the
// the whole summary to the next input section
section.hide();
summary.show();
$('#summary').prependTo($('#education'));
}
</script>
Note that the above is just a sketch of the idea. The idea is that you keep updating the summary, showing the updated section, hiding the data just input, then moving the summary box to the top of the next section.
When they click the final save button, although your sections are hidden, the will still get submitted.
One easy alternative us to simply do an Ajax save when they add a new section/ for example they click to add a new school, save the prior section or simply put a save button next to each section and when they finish each section they click save which does an ajax call to save only the recent changes. This would be accomplished using a jQuery .Ajax() call.