javascript/jquery not working in the partial view. - javascript

I have a main view and in it I have a partial view. In my partial view, I have a table which shows some results of a search carried out. what I want is that when I click on the row, it should alert the data in that row. but this is not happening.
I tried nearly everything on the internet but couldn't find anything.
Partial view:
#model List
<string>
<table class="table table-striped" id="tblGrid">
<thead id="tblHead">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#for (int item = 0; item < Model.Count; item = item + 2)
{
<tr>
<td style="width: 300px">
#Model[item].ToString()
</td>
#{ int temp = item;
item = item + 1;
}
<td style="width: 100px">
#Model[item].ToString()
</td>
#{
item = temp;
}
</tr>
}
</tbody>
</table>
Data is populated just fine, but the javascript is not called.
main:
<head>
<script type="text/javascript">
$(document).ready(function () {
$("#tblGrid tr").live(function () {
$(this).addClass('selected').siblings().removeClass('selected');
var value = $(this).find('td:first').html();
alert(value);
});
});
</script>
</head>
<body>
<input id="searchAttr" name="searchAttr" />
<button href="#myModal" id="openBtn" data-toggle="modal" class="btn btn-default">Search</button>
<div id="searchresults">
</div>
</body>
Any help provided will be appreciated.

place your script tag in body instead of head and then try

Are you trying to use jQuery without connecting your view with it?
Add to the top of of your main this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

Related

How to populate table based on button click

I have a table which contains some data about car makes.
It looks like this:
Now in the table appears data for all makes, but I need to show data only for the make that I've clicked. For example if I click on Audi to show data only for this make.
This is my view where I have populated the table:
<div class="row">
#{var testList = Model.ProductMatchingVehicles.GroupBy(p => p.Make.Name).ToList(); foreach (var item in testList) {
<div class="btn btn-danger btnMake" data-id="#item.Key" id=btnMake onclick="myFunction()">#item.Key</div>
} }
</div>
<div class="row">
<div class="col-xs-12">
<table class="table table-condensed table-striped table-bordered">
<thead>
<tr>
<th>Make</th>
<th>Model</th>
<th>Engine</th>
<th>Data</th>
<th></th>
</tr>
</thead>
<tbody>
#if (Model.ProductMatchingVehicles != null) { foreach (var item in Model.ProductMatchingVehicles) {
<tr>
<td>#item.Make.Name</td>
<td>#item.Model.Name</td>
<td>#item.Engine.Name</td>
</tr>
} }
</tbody>
</table>
</div>
</div>
Can you please advise me how to achieve this in javascript or jquery? Thanks!
You can try with following code:
1) Modify <tbody> as follows:
<tbody>
#if (Model.ProductMatchingVehicles != null) { foreach (var item in Model.ProductMatchingVehicles) {
<tr class="vehicle_rows" data-refId="#item.Key">
<td>#item.Make.Name</td>
<td>#item.Model.Name</td>
<td>#item.Engine.Name</td>
</tr>
} }
</tbody>
Here we have added the class and data-refId attribute to each <tr>
2) Modify the button click function a bit:
<div class="btn btn-danger btnMake" data-id="#item.Key" id=btnMake onclick="myFunction(this)">#item.Key</div>
Here passing this reference to function
3) The function myFunction will have logic something like this:
function myFunction(obj){
var $button = $(obj);
var car_make = $button.data("id"); //reading the data-id of clicked button
//hide all rows first
$(".vehicle_rows").hide();
//show only currenly clicked buttons associated rows
$(".vehicle_rows[data-refId="+car_make+"]").show();
}

How to avoid creating new row in table after javaScript call?

I'm building a laravel application where I want to show if there is any update data in database after two seconds.So in this scenario I have given the table a 'id' and then I have laod the table after certain time interval. But the problem is after every javascript call it creates an empty row in table even if the table retrieve the value also. How do I avoid the problem..any suggestion please?
<div class="container">
<h3> List Of Courses </h3></br>
<table class="table table-striped table-bordered dataTable" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Title</td>
<td>Description</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($items as $row)
<tr>
<td>{{$i}}</td>
<td class="title" data-id1="{{$row->id}}" contenteditable>{{$row->title}}</td>
<td class="description" data-id2="{{$row->id}}" contenteditable>{{$row->description}}</td>
<td>
<button type="button" onclick="deleteItem({{ $row->id }})" class="btn btn-danger">Delete</button>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
Here is the javascript I have to use to load the table after 3 seconds:
<script type="text/javascript">
setInterval(function() {
$("#example").load("list #example");
}, 30000);
</script>
You need to give load a callback and check if you returned any data.
Without knowing the return data structure my best guess would be
$("#example").load("list #example", function (data) {
// hopefully you are returning json. if not, return json. It's the artisan way :D
let parsed = JSON.parse(data);
if (parsed) {
// build html and inject in dom
}
});
See this is how I actually solved the problem,
I put the table inside a new div and I called the jquery .load() on that div.
Like this :
<div class="reloadTable">
<table class="table table-striped table-bordered dataTable" id="example">
// table data
</table>
</div>
javaScript :
<script type="text/javascript">
setInterval(function() {
$(".reloadTable").load("list #example");
}, 3000);
</script>

Want to move an added element to a different part of the DOM

I'll try and state what im trying to do and hope it makes sense (i only learned this last week!). When clicking the delete button that i create, i would like the content associated along with it to go down into a panel body i created in my HTML page with a class name of 'panelAdd'. Any help is much appreciated as i am quite new. Thanks for reading. Ill put the HTML first
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/darkly/bootstrap.css" crossorigin="anonymous" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>To Do List</title>
</head>
<body>
<h3 class="header">
<strong>To Do List</strong>
</h3>
<table class="table table-responsive myTable col-xs-offset2" id="myTable">
<thead>
<th>Complete?</th>
<th>Task to Complete</th>
<th>Time to Complete?</th>
<th>Remove?</th>
</thead>
<tbody>
<tr>
</tr>
<tr>
<td><input type="checkbox" class="newCheck col-xs-offset-2" value=""></td>
<td><input type="text" class="newWord" placeholder="New task"></td>
<td><input type="text" class="newTime" placeholder="How long do you have?"></td>
<td><button class="btn btn-primary buttonAdd">Add Task</button></td>
</tr>
</tbody>
</table>
<footer>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Completed!</h3>
</div>
<div class="panel-body"></div>
</div>
</footer>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/add.js"></script>
<script type="text/javascript" src="js/remover.js"></script>
</body>
</html>
Add button
$(document).ready(function (){
$(".btn-primary").on("click", function(e) {
e.preventDefault();
var newWord, newRow, wordTd, newCheck, deleteButton, deleteTd;
var isDuplicate;
newWord = $(".newWord").val();
newTime = $(".newTime").val();
newCheck = $(".newCheck").val();
var newRow = $("<tr>");
var newCheck = $("<input>").attr("type", "checkbox").attr("class", "newCheck").attr("data-state", "not-checked");
var wordTd = $("<td>").append(newWord).before();
var timeTd = $("<td>").append(newTime).before();
var deleteButton = $("<button>").addClass("btn btn-danger buttonRemove").append("Remove");
var deleteTd = $("<td>").append(deleteButton);
newRow.append(newCheck).append(wordTd).append(timeTd).append(deleteTd).before();
$("tbody").append(newRow);
$("#newWord").val("")
});
});
$(document).on("click", ".newCheck", function(){
if($(this).prop("checked") === true){
$(this).parent().attr("class", "done");
}
else{
$(this).parent().removeClass();
}
});
Remove Button
$(document).ready(function (){
$(document).on("click",".btn-danger", function(){
$(this).parents("tr").remove();
});
});
FIDDLE
Remove Button
$(document).on("click",".btn-danger", function(){
$t = $(this).closest('tr').find('td')[0];
$(this).parents("tr").remove();
$('.panel-body').append($t);
});
});
What you can do is grab the content you want to insert and append it in the target panel in this case .panel-body. See the fiddle above which adds the task name to the Completed list.
Do you expect like this.
Fiddle Sample
Code snippets:
$(document).on("click",".btn-danger", function(){
var removed = $(this).parents("tr").remove();
$(".panel-body").append('<div class="panelAdd"></div>').append(removed);
});
Let me know if this helps!
DEMO
You can just use .detach and .appendTo on click event of your remove button as below:
$(document).on("click",".btn-danger", function(){
var detachedRow=$(this).parents("tr").detach(); //detach and store it as reference
detachedRow.find('input[type="checkbox"]').remove();
//I hope you don't need checkbox when task is complete so removing it from that row
detachedRow.appendTo($('.panel .panel-body #myTableCompleted tbody'));
append it to your completed panel
});
Note : The .detach() method is the same as .remove(), except that
.detach() keeps all jQuery data associated with the removed elements.
This method is useful when removed elements are to be reinserted into
the DOM at a later time.
I have also added the table structure in your .panel-body to get the same UI look and have removed column for checkbox from the same and it is as below:
<div class="panel-body">
<table class="table table-responsive myTable col-xs-offset2" id="myTableCompleted">
<thead>
<th>Task to Complete</th>
<th>Time to Complete?</th>
<th>Remove?</th>
</thead>
<tbody>
</tbody>
</table>
</div>
Note - I think there might be other requirements too like only checked
checkbox to be added to that completed panel-body etc., and if yes
there will be a minor change in the delete code

Popover not showing on first click for dynamically generated content

I'm trying to get a popover for my webpage. It doesn't work for me on the first click but however works fine thereafter. I realize that it gets instantiated on the first click and therefore doesn't show up. Is there a better way to instantiate it, given that I'm using id's that are generated at runtime. I have looked at similar questions but they don't seem to work for me. Here is the code I have written,
<table id="userInfo">
<thead>
<tr>
<th>UserGroup</th>
</tr>
</thead>
<tbody>
<% #userdetails.each do |user| %>
<tr>
<td>
<a class='user_show_more' data-placement='left' id='<%= user %>'>[+]</a>
<!-- popover table starts here -->
<div id="<%= user %>_popover" style="display: none">
<table>
<thead>
<tr>
<th>UserNames</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<%= user['name'] %>
</td>
</tr>
</tbody>
</table>
</div>
<!-- popover ends here -->
<% user['group'] %>
</td>
</tr>
<% end %>
</tbody>
</table>
And my javascript code looks like this,
$('.user_show_more').on('click', function (e) {
var $this = $(this)
var popover_id = '#'+$this.attr("id");
$(popover_id).popover({
html : true,
content: function() {
var popover = '#'+$this.attr("id")+'_popover';
return $(popover).html();
}
});
});
You can add two click handlers to your popovers. The first one uses 'one' and the second one uses 'on'.
https://jsbin.com/kegovebufu/1/edit?html,js,console,output
HTML
<button type="button"
class="btn btn-lg btn-danger"
data-toggle="popover"
id="Temp"
>Stuff</button>
<script type="text/html" id="Temp_popover">
<div>
<table>
<thead>
<tr>
<th>UserNames</th>
</tr>
</thead>
<tbody>
<tr>
<td>blah</td>
</tr>
</tbody>
</table>
</div>
</script>
Javascript
function PopoverClick()
{
$(this).popover('toggle');
}
$('[data-toggle="popover"]').one('click',function(e){
console.log('once');
var _this = $(this);
_this.popover(
{
html:true,
content: function()
{
return $('#'+$(this).attr("id")+'_popover').html();
},
trigger: 'manual',
placement:'right'
}).popover('show');
_this.on('click',PopoverClick);
});

Datatables.net post whole table

I am using DataTables Table plug-in for jQuery and am having an issue retrieving posting data between the different pages.
So I have a checkbox in each row on the table. If a user selects a checkbox on page 1 then switches to page 2 and selects a checkbox and then submits, the controller then receives a blank object. If they submit from page 1 I can see the items from the first page. Is there a way to post the whole table?
Second issue, I have two buttons at the bottom that should do two different things. So either I could call to the method and then determine which button was pressed or just call that specific method. How do I accomplish this?
Razor Code
#using (Html.BeginForm("ManageSelected", "Home", FormMethod.Post, new { id = "ManageApplicationForm" }))
{
<table id="example" class="table table-striped table-bordered table-condensed" width="100%">
<thead>
<tr>
<th> </th>
<th>Student Name</th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.Students.Count(); i++)
{
#Html.HiddenFor(x => x.Students[i].Student.StudentUserID)
<tr>
<td style="width: 1px">#Html.CheckBoxFor(model => model.Students[i].IsSelected)</td>
<td>#Model.Students[i].Student.User.FullName() </td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-primary btn-action" id="acceptBtn" value="Accept" name="command">Accept</button>
<button type="submit" class="btn btn-primary" value="Decline" name="command">Decline</button>
}
Controller stub
public ActionResult ManageSelected(AdminManageApplicationsViewModel model, string command)

Categories