Passing CSS Values Through JavaScript to Partial View - javascript

I am working with an MVC Entity Framework Webapp. I have a view that displays other partial views that are updated every 30 seconds. The issue is the dynamic progress bar I am using does not fill up at all and I have tried everything I know. The problem I think is the css that gets passed to the partial view ("width", current_progress + "%"). Here is a pic and the bar is supposed to be over half full...
Controller methods:
public ActionResult Dashboard()
{
ViewBag.SumofDon = db.tblDonors.Sum(s => s.DonationAmount);
return View(db.tblDonors.ToList());
}
public ActionResult Progress()
{
return PartialView("_Progress", db.tblDonors.ToList());
}
Dashboard.cshtml:
#model IEnumerable<bssp.Models.tblDonor>
#{
ViewBag.Title = "Dashboard";
}
#section Scripts{
<script>
function loadProgressPV() {
$.ajax({
url: "#Url.Action("Progress")",
type: 'GET', // <-- make a async request by GET
dataType: 'html', // <-- to expect an html response
success: function(result) {
$('#progress').html(result);
}
});
}
$(function() {
loadProgressPV(); // first time
// re-call the functions each 10 seconds
window.setInterval("loadProgressPV()", 10000);
});
</script>
<script>
$(function () {
var SumofDon = #ViewBag.SumofDon;
var current_progress = (SumofDon / 20000) * 100; // 20000 is the goal that can be changed
$("#dynamic")
.css("width", current_progress + "%") //This causes the problem?
});
</script>
}
<div class="container-fluid">
<div class="row" id="progress">
#Html.Partial("_Progress")
</div>
</div>
Partial view:
#model IEnumerable<bssp.Models.tblDonor>
<div class="row">
<br /><br /><br />
<div class="col-md-12">
<div class="well bs-component">
<h4>#String.Format("{0:C}", #ViewBag.SumofDon) out of $20,000<br /></h4>
<div class="progress progress-striped active">
<div class="progress-bar" id="dynamic" style="width: 0%"></div> #*The width is what gets updated because it found the id of dynamic*#
</div>
</div>
</div>
</div>
Any help would be awesome and thanks in advance!

I think your issue is that you pull in the html from the partial with a style="width: 0%" but then jQuery that adjusts the css, $("#dynamic").css("width", current_progress + "%"), is only run on page load, not after the partial reloads. You have two options to fix this,
Run the jQuery function after the razor loads in from the partial, in the success method of the ajax.
Since you are using razor to create the partial, why not just do the calculation right there? That way the partial comes in already set up with the width set. This is the easier and faster option of the two.

Related

Click on class is not working after template render from laravel

I am using Jquery ajax to get template from Laravel,
$(".menugroupbutton").on('click', function() {
jQuery.ajax({
url: "/menu/renderitems",
data: {item_group: this.id },
type: "POST",
success:function(data){
$data = $(data); // the HTML content that controller has produced
$('#itemcontainer').hide().html($data).fadeIn();
}
});
});
};
Here is HTML which is currently in current blade template,
<div class="row" style="padding-left: 15px" id="itemcontainer">
#include('pages.menu.renderitems')
</div>
the template which going to be rendered on menugroupbutton click is
#foreach($items as $i)
<div class="col-lg-2 bg-light-info px-6 py-8 rounded-xl mr-2 mb-2 click2add">
{{$i->item_name}}</br>
{{$i->item_price}}
</div>
#endforeach
Here is click2add event,
$('.click2add').on( 'click', function () {
console.log('test');
});
I have one more onclick event on class click2add.
Now problem is,
When first time page is loaded, my click event on class click2add is working fine, means it show test in console
But when i render template(which have click2add class) with .menugroupbutton, click2add event is no more working, no console log of test.
How can I make click event working on render template as well?
Thanks,
Your jQuery code should be:
$('#itemcontainer').html($data).fadeIn(); //Remove hide()
Working Fiddle
Hope this will be useful.

Can someone explain to me why this isn't working? Ajax Load + scripts on html

The script won't load after the ajax has loaded the html content, why is this simply step not working. Here is what I got:
MakoStart.html: (The main page that will change)
<div class="makoislandintro" id="makochange">
<div class="makochoicesfirst">
<img src="../img/makoislandspecial/makobeach.jpg" class="makoislandbeach" id="makoislandbeach" alt="current">
<br>
</div>
</div>
<script>
document.getElementById("makoislandbeach").onclick = function() {
$('#makochange').load('makoisland.html');
};
</script>
This works, when i click the image with the id: makoislandbeach, the content changes to whats in makoisland.html.
Here is what is in makoisland.html:
<div class="makochoices">
<div id="rightside">
<img src="../img/makoislandspecial/waterstream.jpg" class="makoislandchoice" id="waterstream" alt="right choice">
</div>
<div id="leftside">
<img src="../img/makoislandspecial/islandside.jpg" class="makoislandchoice" id="islandside" alt="left choice">
</div>
</div>
<script>
document.getElementById("waterstream").onclick = function() {
$('#makochange').load('waterstream.html');
};
document.getElementById("islandside").onclick = function() {
$('#makochange').load('islandside.html');
};
</script>
Once the content changed, the script doesn't execute when i click the 2 new images that have replaced the old content. I have made a waterstream.html, it is the same as makoisland.html but with different images, but the script won't work after the first transition.
Take a look at this answer. As it said:
When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.
Maybe you could do something like this. Instead of using load, use ajax. It's slightly different.
<div class="makoislandintro" id="makochange">
<div class="makochoicesfirst">
<img src="../img/makoislandspecial/makobeach.jpg" class="makoislandbeach" id="makoislandbeach" alt="current">
<br>
</div>
</div>
<script>
document.getElementById("makoislandbeach").onclick = function() {
$.ajax({
url: "makoisland.html",
context: document.body,
success: function(responseText) {
$("#makoislandbeach").html(responseText);
$("#makoislandbeach").find("script").each(function(i) {
eval($(this).text());
});
}
});
};
</script>

Issues with jScroll

I'm attempting to use jScroll to load a partial view repeatedly, based on an incrementing page number. This partial view gets back a few divs, nothing special. In order to have infinite scrolling, the partial view must return the hyperlink tag in order to allow itself to find the next page to load (as far as I am aware, at least.)
So we have the partial view,
Partial View:
<div class="someClass"></div>
<div class="someOtherClass"></div>
<a class="jScroll-next" href="some/path/to/resource?pagenumber=1">
The view in which the partial view is placed repeatedly,
View:
<div id="PrimaryDiv">
#PartialView
</div>
And the jQuery that helps power and link it all together.
jQuery:
$(document).ready(function (){
var pn = 1;
function incrementAndSet(){
pn +=1;
$('.jScroll-next').prop("href","some/path/to/resource?pagenumber=" + pn);
}
$(#PrimaryDiv).jscroll({
autoTrigger: true,
nextSelector: '.jScroll-next',
callBack: function(){incrementAndSet();}
});
});
My issue is that, even though the next link is being populated, it's not being used. Example output:
1st scroll:
<div id="PrimaryDiv">
<div class="someClass">datavalueforpage1</div>
<div class="someOtherClass">somedataonpage1</div>
<a class="jScroll-next" href="some/path/to/resource?pagenumber=2">
</div>
2nd scroll:
<div id="PrimaryDiv">
<div class="someClass">datavalueforpage1</div>
<div class="someOtherClass">somedataonpage1</div>
<div class="someClass">datavalueforpage1</div>
<div class="someOtherClass">somedataonpage1</div>
<a class="jScroll-next" href="some/path/to/resource?pagenumber=3">
</div>
I figured out a solution part way through the post, thought I'd share it anyway.
It was mostly me derping on scope. Moving:
var pn = 1;
and
function incrementAndSet(){
outside of the
$(document).ready(function (){
allowed me to utilize the counter (pn) in the
$(document).ready(function (){
of the partial view, meaning I could call the incrementAndSet()function on the partial view, ensuring that the data was properly set when the partial view was ready.
So my files look similar to this:
Partial View:
.../Partial.js
<div class="someClass"></div>
<div class="someOtherClass"></div>
<a class="jScroll-next" href="some/path/to/resource?pagenumber=1">
Parent View:
.../Parent.js
<div id="PrimaryDiv">
#PartialView
</div>
Partial jQuery file:
$(document).ready(function (){
incrementAndSet();
});
Parent jQuery file:
var pn = 1;
function incrementAndSet(){
pn +=1;
$('.jScroll-next').prop("href","some/path/to/resource?pagenumber=" + pn);
}
$(document).ready(function (){
$(#PrimaryDiv).jscroll({
autoTrigger: true,
nextSelector: '.jScroll-next',
callBack: function(){incrementAndSet();}
});
});

Insert HTML with AngularJS code inside

any help about who insert html with Angular code inside the html string.
Example:
<div class="container">
<span class='btn' onclick="javascript: clicklink()">click here</span>
<div name="content" id="content">
</div>
</div>
<script>
function clicklink(){
$("#content").html("<span class='label label-danger'>Invoice</span>"+
" <div ng-app ng-init='qty=1;cost=2'> <b>Total:</b> {{qty * cost | currency}} </div>");
}
</script>
Example click here
If you're looking for a 'Hello World' kind of example, this is probably as basic as it gets.
https://code-maven.com/hello-world-with-angular-controller
Maybe the example doesn't make sense, but here is the thing maybe exist another way to do that. I have a project with c# MVC and for render some Views I use ajax
Javascript to load modal into View:
function Edit(){
$.ajax({
url: '../Controller_/Action_',
type: 'POST',
datatype: "html",
traditional: true,
data: { data1: data1 },
success: function (result) {
$('._container').html(result);
},
error: function (result) { }
});
}
MVC c# code:
public ActionResult Edit()
{
...\ code \...
return PartialView("/View/_Edit", model);
}
View Main:
Open Modal
<div name="_container">
<!-- Here load body of modal -->
</div>
Partial view (Edit) return by Action (Edit) in Controller . Should be a modal structure:
<div name="_editModal">
#html.LabelFor( x => x.Name)
#html.EditorFor( x => x.Name)
<div ng-app ng-init="qty=1;cost=2">
<b>Invoice:</b>
<div>
Quantity: <input type="number" min="0" ng-model="qty">
</div>
<div>
Costs: <input type="number" min="0" ng-model="cost">
</div>
<div>
<b>Total:</b> {{qty * cost | currency}}
</div>
</div>
</div>
As already stated by a bunch of people in the comments and other answers this is absolutely bad practice. But there is also a built-in option to solve your problem with pure AngularJS using $compile.
In order to make that work you need to place everything inside a controller or directive and inject the $compile service accordingly.
You need to use the $compile service to produce a function of your dynamic HTML markup which is able to consume a scope object as a parameter in order to produce a working AngularJS template.
After inserting your template, you need to trigger the AngularJS digest cycle using $apply.
<div class="container" ng-controller="MyController">
<span class='btn' ng-click="clicklink()"">click here</span>
<div name="content" id="content">
</div>
</div>
<script>
app.controller("MyController", function($scope, $compile) {
var template = "<button ng-click='doSomething()'>{{label}}</button>";
$scope.clicklink = function(){
$scope.apply(function(){
var content = $compile(template)($scope);
$("#content").append(content);
});
}
});
</script>

Change the content of 3 divs using javascript and ajax

i'm using rails 4 and javascript and here's my question:
i need to change the values of 3 divs using a button. The values of the divs are generated by a ruby function that came from the controller of that page.
Code:
<% $number= randNumbers %>
<div id="1"><%= $number[0] %></div>
<div id="2"><%= $number[1] %></div>
<div id="3"><%= $number[2] %></div>
<button id="btn1" >Click me!</button>
Here's the ruby method
def randNumbers
n1=rand(1..10)
n2=rand(1..10)
n3=rand(1..10)
return array=[n1,n2,n3]
end
So i need to recall the ruby function to generate new random numbers everytime i click on the button "btn1" without reloading the page.
I know that i have to use ajax or jquery, but i do not really know how to use it with ruby methods.
Thanks for helping :D
You can try the following:
HTML code in View:
Remove the code <% $number= randNumbers %>
Change the code to:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<button id="btn1" >Click me!</button>
Javascript Code in View:
$( document ).ready(function() {
call_ajax();
});
$("#btn1").click(function(){
call_ajax();
});
function call_ajax(){
$.ajax({ type:'POST', url:'/controller/get_random', data: {},
success:function(data)
{
$("#1").text(data.arr[0])
$("#2").text(data.arr[1])
$("#3").text(data.arr[2])
},
error:function()
{
// Handle error if Ajax fails
}
});
}
Method in Controller:
def get_random
n1=rand(1..10)
n2=rand(1..10)
n3=rand(1..10)
array=[n1,n2,n3]
render json: {arr: array}
end
Also add routes in routes.rb: post '/controller/get_random'

Categories