jquery within a javascript function not working - javascript

I am calling a javascript function from within my razor code..but the jquery code within my javascript function doesnot get executed..
what is the correct way of doing it.
function getPosition(id) {
var c = '#' + id;
return $c.index();
}
My HTML Table
<tbody>
<tr>
<td>
#foreach(Result geResults in Model.results)
{
#:
<script>
{
getPosition(#geResult.assessmentId);
}
</script>
}
</td>
</tr>
<\tbody>
UPDATE
As everybody is getting confused i am posting more detail
<table>
<thead>
<tr>
#foreach (Assessment geAssessment in Model.assessments)
{
<th id=#geAssessment.AssessmentID>#geAssessment.Name</th>
}
</thead>
<tbody>
<tr>
#{
// add a td for each assessment in body
foreach(Assessment geAssessment in Model.assessments)
{
<td>
#foreach (ShortResult geResult in Model.results)
{
#:
<script>
{ getPosition(#geResult.assessmentId);
}
</script>
}
</td>
}
}
</tr>
</tbody>
i want to return the column index in getPosition function and then print it in the td..hope this clears out any confusions
currently it says getPosition is out of context whereas intellisense shows me getPosition when i code

Just put c in brackets. It will be like this:
function getPosition(id) {
var c = '#' + id;
return $(c).index();
}
If it doesnt throw
$ Undefind error

first of all check that your passing the values means getPosition("") is not null secondly write in JavaScript
function getPosition($id) {
var c = '#' + $id +;
return $(c).index();
}

Related

I want to apply onclick in JavaScript without touching the HTML part so that on clicking a single th tag I will get an alert message

This is my code where I am trying to make a to-do list in which due-date, edit delete and task to be completed are the headers. But I have to apply onclick handler only on due-date so that as soon as I click the duedate column I will get the alert message but the onclick should be only applied in the JavaScript part not the HTML. And I have to take help of id in thead tag.
var edit=function editClickHandler(){
alert("Edit");
}
var del=function deleteClickHandler() {
alert("DELETE");
}
var duedate1=function ddate(){
alert("Due Date1");
}
function myFunction(x) {
alert(x.cellIndex);
}
function init() {
var table = document.body.children[0];
var t1 = table.getElementsByTagName('thead');
var t2 = t1.getElementsByTagName('tr');
var t3 = t2.getElementsByTagName('th').getElementById('ding');
t3.onclick = duedate1;
}
init();
I think the code would explain it better than I will write paragraphs
You were trying to access a method that did not exist, t1.getEl ... => t1 [0] .getEl
var duedate1=function ddate(){
alert("Due Date1");
}
//You form without error
function init() {
var table = document.body.children[0];
var t1 = table.getElementsByTagName('thead'); // getElementsByTagName retun an object
console.log(t1);
var t2 = t1[0].getElementsByTagName('tr');
var t3 = t2[0].getElementsByTagName('th')[0]
t3.addEventListener("click", duedate1);
}
//Another simplified form
function init2 () {
document
.getElementById("myColumnWithEvent")
.addEventListener("click", duedate1);
}
init();
init2();
<html>
<head></head>
<body></body>
<table>
<thead>
<tr>
<th>
Column 1
</th>
<th id='myColumnWithEvent'>
Column 2
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Loremipsum</td>
<td>Loremipsum</td>
</tr>
<tr>
<td>Loremipsum</td>
<td>Loremipsum</td>
</tr>
</tbody>
<table>
</html>
Documentation:
https://www.w3schools.com/jsref/met_element_getelementsbytagname.asp
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
You can use document.getElementById().addEventListener() in your JavaScript:
document.getElementById('myLink').addEventListener('click', function() {
alert('The link was clicked!');
});
This is my link

using forEach with SignalR return value (List<string>) in javascript

Hi i invoke a method with using SignalR and i want to use return value as foreach loop in javascript for create a table
Hub :
public void OrderAllSales()
{
List<string> tableValue = new List<string>();
/*
Do something and fill tableValue with
<tr>
<td>....</td>
<td>....</td>
</tr>
block for every item
*/
Clients.All.SendListOfAll(tableValue);
}
Cshtml
<table class="table">
<thead>
<tr style="margin-left: 10px">
<td>Price (₺)</td>
<td>BTC (฿)</td>
<td>Total (₺)</td>
</tr>
</thead>
<tbody id="HistoryGrid">
</tbody>
</table>
JavaScript :
<script>
$(document).ready(function () {
var bitcoinHub = $.connection.bitcoinHub;
$.connection.hub.start().done(function () {
$("#allSales").click(function () {
bitcoinHub.server.orderAllSales();
});
bitcoinHub.client.sendListOfAll(function (x) {
x.forEach(Create);
});
});
function Create(item) {
$("#HistoryGrid").prepend(item);
}
});
</script>
i can invoke server method but i couldn't use this return value for create a table
i figure out it.
Wrong Code :
bitcoinHub.client.sendListOfAll(function (x) {
x.forEach(Create);
});
Right Code :
bitcoinHub.client.sendListOfAll = function (x) {
x.forEach(Create);
};
The error is using () instead of = while trying catch returning method at client side.

Create a select from list and put it in table

I'm writing a web application using Java and Spring.
From the controller, I send to the view a list called materials
#RequestMapping(value = "/advanced")
public String advancedCalculation(Model model) {
model.addAttribute("materials", materialService.getMaterials());
model.addAttribute("calcForm", new CalculationForm());
return "advanced";
}
materials is a list of objects called MaterialDTO:
public class MaterialDTO extends DTO {
/* Constructors */
public MaterialDTO() { super(); }
public MaterialDTO(Integer id, String name) { super(id, name); }
}
From the client side I have to make tables with buttons to add rows to such tables. Something like:
<table id="1">
<thead>
... 2 columns ...
</thead>
<tbody>
<tr>
<td>HERE I NEED THE SELECTOR</td>
<td>column 2</td>
</tr>
</tbody>
</table>
.
.
.
<table id=N>
<thead>
... M columns ...
</thead>
<tbody>
<tr>
<td>HERE I NEED THE SELECTOR</td>
<td>column 2</td>
...
<td>column M</td>
</tr>
</tbody>
</table>
That selector is the same for all tables, so I wanted to create it from the materials list once and use it where I need it. With this last I'm having problems ...
/* Making select */
var materialsList = new Array();
var sel = $('<select>');
<c:forEach items="${materials}" var="material">
var material = new Object();
material.id = '${material.id}';
material.name = '${material.name}';
materialsList.push(material);
</c:forEach>
$(materialsList).each(function() {
sel.append($('<option>').attr('value', this.id).text(this.name));
});
That's when I try to add it as HTML and it fails
function add_to_table_1() {
$('#1')
.append('<tr><td>' + sel.html() + '</td><td><input type="text" id="e"></input></td><td><input type="text" id="S"></input></td><td><input type="itext" id="r"></input></td><td><button onclick="delete_row(this)">Borrar</button></td></tr>');
}
And instead of the selector appears "[object Object]". How can I fix this?
Try this:
$(sel).wrap('<div></div>').parent().html();
This will fix your select not displaying with your options. Remember .html() only returns innerHTML. The outer html, <select></select>, will not display with it. You have to wrap first.
Alternative:
$(sel)[0].outerHTML

jQuery Click Event for Dynamically Created Links Not Working

I am displaying a list of users in a table. Then, I have a button to allow a user to view more details about a specific user. However, I am having a hard time getting the ID for the user that is clicked on. I am not sure why it's not working. What am I doing wrong? I tried several options, and none of them work.
Partial code of how data the links are generated in my view.
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
My jQuery function
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).attr('id');
console.log('dt');
});
});
I also tried it this way:
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
Here is the Javascript function that I created. It kept giving
function test(e){
console.log(e);
};
I get this error:
0x800a1391 - JavaScript runtime error: 'test' is undefined
updated on 11/21/15 #7:53 AM EST
I removed the for loop and created a single cell with 1 click button. The click event is not registered. I tried it with 'on', 'live', and 'delegate' with no success.
<div class="table table-responsive" style="width:100%;height:100%;">
<table class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th><div class="centerText">Date Created</div></th>
<th colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="6"><div class="centerText">Detail</div></td>
</tr>
</tbody>
</table>
</div>
#section Scripts {
<script type="text/javascript">
$('.table tbody tr td div').delegate('.Detail','click', function ()
{
console.log('you click me');
});
</script>
}
You are trying to get the attribute id which doesn't exist. Use below to get data-id
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).data('id');
console.log(dt);
});
you can also use
var dt = $(this).attr("data-id");
Second one (remove var):
function test(e){
console.log(e);
};
Partial code of how data the links are generated in my view. change id instead of data-id.
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
My jQuery function
$(function () {
$('.Detail').on('click', function (event) {
var dt = $(this).attr('id');
console.log('dt');
});
});
I also tried it this way:
if (Model != null) {
if (Model.Count() > 0) {
foreach (var item in Model) {
<tr>
<td><div class="centerText">#item.UserID</div></td>
<td><div class="centerText">#item.FirstName</div></td>
<td><div class="centerText">#item.LastName</div></td>
<td><div class="centerText">Details</div></td>
</tr>
}
}
}
Here is the Javascript function that I created. It kept giving. (Remove var before function).
function test(e){
console.log(e);
};
Here is how I reproduced your problem with JavaScript runtime error: 'test' is undefined.
Scenario
I guess that you've defined the function test probably in your jQuery DOM ready function $(function(){...}.
If so, the function test is undefined because by the time the DOM is loading, AND the event handlers on DOM elements are being registered (in your case the onclick in the link), the function test is not yet known to the document, and therefore undefined.
Solution
Try to move your test function's declaration outside of jQuery's DOM ready function. That is,
$(function(){
//code that has to run once the DOM is ready
});
function test(e){
console.log(e);
}
DEMO
I found what was causing the problem. I had a modal popup within the form. I was looking to add a textarea, so I added this code '
<textarea name="reasonForArchiveText" id="reasonForArchiveText" />
That's the code that was preventing me from getting the click event. As I was playing around with the code, I commented out the modal popup, and things started to work. Then, I commented section of the modal until I finally found the culprit. The minute that I commented it out, the code works.

Onclick in td - access next cells

I'm using a table to display items, an onclick event on cell[0] should output (alert) the data from cell[1] and cell[2].
I'm not sure with which approach I could access them.
Here is my code so far
http://jsfiddle.net/5uua7eyx/3/
Perhaps there is a way to use my variable input
HTML
<table id="items">
<tr>
<td onclick="ClickPic(this)">Picture0</td>
<td>Name0</td>
<td>Price0</td>
</tr>
<tr>
<td onclick="ClickPic(this)">Picture1</td>
<td>Name1</td>
<td>Price1</td>
</tr>
</table>
JS
function ClickPic(e) {
"use strict";
var input = e.target;
alert("Clicked!");
}
Thank you
You're passing this, which represents the element clicked, not the event object.
All you need to do is use the parameter to get the sibling .cells from the .parentNode, then use the elem.cellIndex to figure out the next indices:
function ClickPic(elem) {
"use strict";
var cells = elem.parentNode.cells;
var currIdx = elem.cellIndex;
alert(cells[currIdx + 1].textContent + " " + cells[currIdx + 2].textContent);
}
<table id="items">
<tr>
<td onclick="ClickPic(this)">Picture0</td>
<td>Name0</td>
<td>Price0</td>
</tr>
<tr>
<td onclick="ClickPic(this)">Picture1</td>
<td>Name1</td>
<td>Price1</td>
</tr>
</table>
x
If you know the index numbers will always be 1 and 2, then you can shorten it.
alert(cells[1].textContent + " " + cells[2].textContent);
you can change your js function to something like this
<script type="text/javascript">
function ClickPic(e) {
var s = '';
$(e).siblings().each(function() {
s = s + ',' + $(this).text()
});
alert(s);
}

Categories