Passing values from view to .js file based on button click - javascript

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
});
});

Related

How to Set Header Text of Modal Dialog According to the Table element and his ID

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 () {
...
...
...
});

Why is this dynamically assigned id using a loop only showing the first assignment? javascript, AJAX & JSTL

Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot

DOM manupulation in meteor

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.

Passing name of button as parameter

I am a newbie in JQuery and ajax and I would like to know if it is possible to pass a value in a function as parameter and using that value as a name of the button which was clicked and proceed with the logic so to send to servlet to handle. I am trying to not use javascript as it is page driven. So what I have in javascript is below.
function test(buttonId)
{
alert(buttonId);
}
The thing is I have a dynamic table which depends on some data I get from the database and as part of the table are some button which I create as I loop through the data and creating the table simultenously. So in one of the rows of my table I have a button with following:
<table id="error_data">
<tr>
<th>Rank</th>Other Table columns names........</tr>
<% for(int rank=1 ; rank<data.size();
rank++) { %>
<tr>
<td>
<input type="button" id="button<%=rank%>" value="Suspend Email" onclick="test('button<%=rank%>')">
</tr>
<%}%>
</table>
I hope I am not verbose in my question I want to be able to click on some button in one of my rows and only deal with data for that row and not refresh anything besides for that row data only. And I think maybe it possible with combination of ajax and jquery some how as ajax is data driven. Any shed of light is highly appreciated, is it possible to try and achieve what I am trying to do. Thank you in advance.

How to call a defined function with parameters with keyboard short keys

I have a table in which i am getting data dynamically. In the table there is an edit button with each record like this
<tr>
.
.
.
//other columns
<td class="center">
<a class="btn btn-info btn-setting edit" href="javascript:;" onClick = "show( 'account_no',<?php echo $row->account_no;?>)">
<i class="icon-edit icon-white"></i>
Edit
</a>
</td>
</tr>
This way i am sending parameter to show method of javascript. Now i am using a keyboard shortcut plugin called shortkeys. When i press down key it adds a class to tr called selected. That's fine i have set it up. Now the problem is that i want to add another shorcut to edit the selected record. Here is the code
shortcut.add("Alt+e",function() {
//???
});
When alter + e is clicked i want to call show method with the parameters defined dynamically. for clearification i want to call show('account_no',<?php echo $row->account_no;?>). But i have no idea how i can do it. Is there any suggestion or alternative? if i can simply call it it would be good as though i have just clicked.
I have doe it using this code.
shortcut.add("Alt+e",function() {
$('.selected > td > a.edit').trigger('click')
});
I am calling click trigger and it is working fine.

Categories