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.
Related
I apologize ahead of time if this question has been addressed...I looked and did not see one. I am building a web app using flask. After successfully logging in the user is routed to index.html via the following code:
#blueprint.route('/index')
#login_required
def index():
return render_template('home/index.html', segment='index')
My index.html includes an ajax request which builds and returns custom html such as:
<div class="card" style="max-width: 22rem;">
<!-- Card content -->
<div class="card-body pb-3">
<!-- Title -->
<h4 class="card-title font-weight-bold">TailNumber</h4>
<h6 class="card-subtitle text-muted d-flex justify-content-between">
<p>AircraftType</p>
<p>Operator</p>
</h6>
<div class="collapse-content">
<div class="collapse" id="tail_number" style="">
<table class="table table-borderless table-sm mb-0">
<tbody>
<tr>
<td class="font-weight-normal align-middle">Engine</td>
<td class="float-right font-weight-normal">
<p class="mb-1">2.5<span class="text-muted">IPS</span></p>
</td>
</tr>
</tbody>
</table>
</div>
<hr class="">
<button class="btn" type="button" data-toggle="collapse" data-target="#tail_number"
aria-expanded="false" aria-pressed="false" aria-controls="tail_number">Show
</button>
</div>
</div>
</div>
I also include a javascript function designed to change the text of my "collapse" button from "Show" to "Hide" and back again as the content is expanded and collapsed:
$(document).ready(function() {
$('[data-toggle="collapse"]').click(function() {
$(this).toggleClass("active");
if ($(this).hasClass("active")) {
$(this).text("Hide");
} else {
$(this).text("Show");
}
});
});
While the collapse feature of my html code works the text is not being updated. If I hard code the html instead of loading it via my ajax request then the button text changes as advertised. My assumption is that the javascript above is not being applied to the html returned by the ajax request but I am not sure how to verify this or, more importantly, correct it. My simplified ajax request is here:
<script>
$(function(){
function update_fleet_view(){
// create an ajax request
var req = new XMLHttpRequest();
req.open("GET", "/ajax", true);
req.send();
req.onload = function () {
// update page with new fleet view
var data = JSON.parse(req.responseText);
document.getElementById("fleet_view").innerHTML = data["fleet_view"];
// timeout to run again after 1 minute
setTimeout(update_fleet_view, 60000);
}
}
// call the function to get it started
update_fleet_view();
})();
</script>
Event delegation was exactly what I needed...thanks for the link James.
I ended up with the following modifications to my JS:
$(document).ready(function() {
$("#fleet_view").on("click", '[data-toggle="collapse"]', function() {
if ($(this).hasClass("collapsed")) {
$(this).text("Hide");
} else {
$(this).text("Show");
}
});
});
where "fleet_view" is the "id" that is referenced by my ajax script.
I attempted to leave the $(this).toggleClass("active") in the script however I could never get it to toggle. Rather than spending precious time tracking that issue down I decided to look at the "collapsed" field as the click event toggles that automatically. I also had to modify my button to add the "collapsed" class otherwise the button text would not update for the first round of clicks (see code below). The "if/else" statement seems backwards but I assure you it works as intended. Again, I can only assume that the "collapsed" class gets added or removed after this script executes.
<button class="btn collapsed" type="button" data-toggle="collapse" data-target="#tail_number"
aria-expanded="false" aria-pressed="false" aria-controls="tail_number">Show
</button>
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.
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>
my html code
<div class="gridRowsContainer">
<div ng-repeat="item in ActiveUserData.ListModel track by $index" class="">
<!-- Checkboxes Generated/inserted here by ajax -->
<div class="gridRow pnl-no-dimiss" ng-style="getRowCss(item)" id="user_list_07c4ab10-4ad0-44d1-9d65-aeee70be20a6" style="background-color: transparent;">
<div>
<div class="userLight listViewRow">
<div class="ms-ChoiceField f-choice" data-hint="Users" data-value="SelectItem">
<input id="selectUser_07c4ab10-4ad0-44d1-9d65-aeee70be20a6" class="ms-ChoiceField-input dataListField ng-valid ng-dirty ng-valid-parse ng-touched" type="checkbox" ng-model="item.isChecked" ng-change="UpdatedSelectedUsers(item)" tabindex="0" aria-checked="false" aria-invalid="false">
</div>
</div>
</div>
</div></div></div>
My jQuery Code
$(":checkbox").change(function() {
$(this).closest('[ng-repeat*="item"]').nextAll('[ng-repeat*="item"]:lt(3)').find('[type="checkbox"]').prop('checked', this.checked);
});
so it not working when content is loaded via ajax , any idea how to make it working when content is loaded via ajax on page load and also more checkboxes entries are loaded when user scroll down .
working jsfiddle with static checkboxes list :: https://jsfiddle.net/mmzth076/7/
but not work with ajax
Try adding the change function in the success handler of the ajax:
$.ajax {
method: 'GET',
success: function() {
load_grid(); //Code that builds the grid with the checkboxes
$(":checkbox").change(function() {
$(this).closest('[ng-repeat*="item"]')
.nextAll('[ng-repeat*="item"]:lt(3)')
.find('[type="checkbox"]')
.prop('checked', this.checked);
});
}
}
You can also use any known parent of the grid that is available in the DOM at the time of binding the click event handler.
$('body').on('change', ":checkbox", function () {
$(this).closest('[ng-repeat*="item"]')
.nextAll('[ng-repeat*="item"]:lt(3)')
.find('[type="checkbox"]')
.prop('checked', this.checked);
});
Replace body with any known predecessor at the time of binding.
When you load contain via ajax, it's it's not going to trigger the the changed event. If you want to trigger, just use jquery and trigger the event manually.
$('checkboxyouwanttotrigger').trigger('change')
var val = '124';
function imagepop(nval) {
val = nval;
}
$(document)
.ready(function () {
$('.ui.selection.dropdown').dropdown();
$('.ui.menu .ui.dropdown').dropdown({
on: 'hover'
});
$('#'+val).popup({
popup: $('.fluid.popup'),
on: 'click'
});
});
Im trying to popup dynamic content coming from database HTML code as below
<div class="extra">
<div id="<?php echo$row['idproperty']; ?>" class="ui more primary button" onclick="imagepop(<?php echo$row['idproperty']; ?>)">
More
</div>
<div class="ui fluid popup top left transition hidden" >
<p><b>Description</b><?php echo$row['description']; ?></p>
<div class="ui three column center aligned grid">
<div class="column"> </div>
</div>
</div>
idproperty is some numbers getting from database i need to show each data in popups please help me to fix this
the function at $(document).ready is called before the function imagepop(nval) which assignes the value of idprperty to val.
The function at $(document).ready is called only once, when the document is done loading, that means that this part of the code:
$('#'+val).popup({
popup: $('.fluid.popup'),
on: 'click'
});
Will not be called when val gets the new value, the one originated from idproperty.
Move that part of the code to the end of your imagepop(navl) function, that should probably fix your issue.
If you still want to have this part of the code run immidiatly as the page loads, you will need to have the true value of idproperty ready to be right then. One way to do this is to include a hideen input field in your HTML and have the PHP feed it the value as a default, and then read this value from your js in the $(document).ready function:
in your html:
<input type="hidden" id="idproperty" name="idproperty" value="<?php echo $row['idproperty']; ?>">
in your $(document).ready function:
val = $(idproperty).val();
$('#'+val).popup({ //... rest of your code here