JQuery Change function not work with ajax content - javascript

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')

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.

jQuery Nested function variable scoping

I cannot get a nested variable value to populate outside a nested function within a button's click event function even though I believe I am using a global variable.
What am I doing wrong to pull value into a console log outside the nested function?
I am creating a shopping cart utilizing jquery pop-up with ajax and php. I am able to add items to the cart as well as add a name & email input field.
When I go to console log in Chrome for the focusout event for the fields they show the values but when trying to use a Checkout button, I am not able to pass the data within the Checkout click outside of a nested function even with a global variable.
--JS--
var formname;
$(document).ready(function() {
...
$(document).on('click', '#check_out_cart', function(){
$('#cart-popover').popover({
html : true,
container: 'body',
content:function(){
return $('#popover_content_wrapper').html();
}
});
$(document).on('click', '#cart-popover', function(){
$('input#namef').focus();
});
$('input#namef').on('focusout', function(){
formname= $('input#namef').val();
console.log(formname);
});
var scart_add = $("input[name='scart_add']").val();
console.log("Scart value is "+scart_add);
console.log("Name is "+formname);
...
});
});
--HTML--
<div class="container">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Menu</span>
<span class="glyphicon glyphicon-menu-hamburger"></span>
</button>
</div>
<div id="navbar-cart" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a id="cart-popover" class="btn" data-placement="bottom" title="Shopping Cart">
<span class="glyphicon glyphicon-shopping-cart-2x"></span>
<span class="badge"></span>
<span class="total_price">$ 0.00</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<div id="popover_content_wrapper" style="display: none">
<span id="cart_details"></span>
<div>
<form method="POST">
Name: <input type="text" id="namef" >
Email: <input type="text" id="emailf" >
<input type="hidden" name="scart_add" value="1" /><br><br>
</div>
<div align="right">
<button type="button" class="btn btn-primary" id="check_out_cart">
<span class="glyphicon glyphicon-shopping-cart"></span> Check out
</button>
<button type="button" class="btn btn-default" id="clear_cart">
<span class="glyphicon glyphicon-trash"></span> Clear
</button>
</div>
</form>
</div>
</div>
<div id="display_item">
</div>
...
</div>
I am expecting the value from the input#namef text to appear in the console.log ...formname variable but it just shows as "".
The event for focusout isn't added to the input until you click the button:
Also, I don't know if it is how you copied and pasted your HTML and Javascript, but it was throwing errors when I put it into a fiddle.
Move this outside of the button click handler as Rory pointed out:
var formname;
$(document).ready(function() {
//Now focusout handler is added on DOM Ready instead of when you click the button
$('input#namef').on('focusout', function(){
formname= $('input#namef').val();
console.log(formname);
});
$(document).on('click', '#check_out_cart', function(){
var scart_add = $("input[name='scart_add']").val();
console.log("Scart value is "+scart_add);
console.log("Name is "+formname);
});
});
Here is a working fiddle: https://jsfiddle.net/hqgv7zsa/
This is a race condition, of sorts.
On document.ready event, you are setting a click event handler
Inside the click handler, you are setting the focusout event handler
Since the click handler is still executing,
immediately, the code runs to show value of scart and formname.
At that time, formname is still empty because the current function
(click event handler) is still executing, and the focusout event, even
if it fires, will fire after that code is executed.
You should move the focusout handler declaration code outside of the click handler code, which will then set both handlers on document.ready() event.
Here's a breakdown of what's happening and when:
var formname;
$(document).ready(function() {
This fires when DOM is loaded (document.ready event)
$(document).on('click', '#check_out_cart', function(){
This fires when user clicks on some element with ID check_out_cart
$('input#namef').on('focusout', function(){
This event handler is only being set once user clicks on cart, but it is not yet executed!
formname= $('input#namef').val();
console.log(formname);
});
This code fires once the event handler has been set for focusout, but still has not executed. Even if a focusout event is fired, it will only execute when the current function exits.
var scart_add = $("input[name='scart_add']").val();
console.log("Scart value is "+scart_add);
Correctly, you will see that formname is empty at this point.
console.log("Name is "+formname);
...
});
});
Hope this explains the flow you're seeing;
Quick fix as in Ryan Wilson's answer, move the focusout handler declaration to the scope of the document.ready handler, outside the click handler.
Using the solution from Unable to fetch values from an input element in Bootstrap's popover, I was able to adjust my JS code to fetch the values with a .find within the .popover-content class that was added by the popover JS.
var formname;
var formemail;
$(document).ready(function() {
//shopping cart
/*load functions*/
load_product();
load_cart_data();
$('#cart-popover').popover({
html : true,
container: 'body',
content:function(){
return $('#popover_content_wrapper').html();
}
});
$(document).on('click', '#cart-popover', function(){
$('input#namef').focus();
});
$(document).on('focusout', '#namef', function(){
formname = $('.popover-content').find('#namef').val();
});
$(document).on('focusout', '#emailf', function(){
formemail = $('.popover-content').find('#emailf').val();
});
$(document).on('click', '#check_out_cart', function(){
var scart_add = $("input[name='scart_add']").val();
var nameval = $("input#namef").val();
alert("Scart value is "+scart_add);
alert("Name is "+formname);
alert("Email is "+formemail);
});
});

use Jquery to click hyperlink

I am trying to create a jquery to click a hyperlink but nothing seems to be working.
HTML
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
no avail
Show all
</div>
what I was trying
$(".warning a").click()
Any suggestions?
Note that jQuery-initiated "click" events will fire the event but will not cause navigation to occur.
Instead you can read the link's HREF attribute and directly set the window location:
// The click event:
$('a').on("click", function() {
console.log("Click event fired");
})
var demo1 = function() {
// This will trigger the click event, but will not navigate.
$(".warning a").click()
}
var demo2 = function() {
// This will navigate but will not trigger the click event. (If you need both to happen, trigger the click event first, and consider delaying the window location update if necessary.)
var url = $(".warning a").attr("href")
window.location = url;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
Show all
</div>
</div>
</main>
<!-- for demo: -->
<button onclick="demo1()">Won't work</button>
<button onclick="demo2()">Will work</button>
jQuery's .click() (without arguments) is a shortcut for .trigger("click"):
function(a,c) {
return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b)
}
Therefore, it will not actually click the element, but just call the click event handlers attached to it, as you can see here:
const $link = $("a");
$link.on("click", () => {
console.log("Clicked? Not really...");
});
$link.click();
$link.trigger("click");
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to get a reference to the actual DOM element and then call HTMLElement.click() on that:
$("a")[0].click();
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can user the vanilla click method:
document.querySelector('.warning > a').click()
// equivalent jquery
//$('.warning > a')[0].click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="warning" role="alert">
no avail
Show all
</div>
Whenever you select div class with hyperlink there you get array because you can have multiple hyperlinks so you need to add somthing like below
Code
$('.warning a')[0].click();
For reference link
Get working example for click event
If I need to redirect, I typically use window.location.href
window.location.href=$(".warning a").attr('href');

Semantic UI checkbox events not triggering after AJAX call

I'm using Semantic UI 2.1 and I have a problem. I have three slider checkboxes in my page. They all have the same class and I can initialize them all at once. They each contain a data-* attribute that I need to send to the server with AJAX calls.
Here's the problem:
After the first time an AJAX call is finished, the events for checkbox no longer work. I know that the events are bound to the DOM and with the change of DOM they won't update but is there any way around it?
Here's a very simple version of my page:
<html>
<body id="body">
<!-- First Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="0" type="checkbox"> <label></label>
</div>
<!-- Second Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="2" type="checkbox"> <label></label>
</div>
<!-- Third Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="3" type="checkbox"> <label></label>
</div>
<button class="button-action">Do Stuff</button>
</body>
<script>
$('.checkbox.comment').checkbox().checkbox({
onChecked: function () {
// This is only called before ajax reload, after ajax, it just won't
console.log("onChecked called");
},
onUnchecked: function () {
// This too is only called before ajax reload
console.log("onUnchecked called");
}
});
$(document).delegate('.button-action', 'click', function () {
$.ajax({
// Noraml ajax parameters
})
.done(function (data) {
if (data.success) {
// Reload
$('#body').load(document.URL + ' #body');
}
});
});
</script>
<html>
You can try to put your checkbox event listener inside a function and call that function each time it reload your page or when you make changes in the document DOM. I've attached a sample code below for reference.
function Checkbox_eventlistener(){
$('.checkbox.comment').checkbox().checkbox({
onChecked: function () {
// This is only called before ajax reload, after ajax, it just won't
console.log("onChecked called");
},
onUnchecked: function () {
// This too is only called before ajax reload
console.log("onUnchecked called");
}
});
}
$(document).delegate('.button-action', 'click', function () {
$.ajax({
// Noraml ajax parameters
})
.done(function (data) {
if (data.success) {
// Reload
$('#body').load(document.URL + ' #body');
Checkbox_eventlistener();
}
});
});
$(function(){
Checkbox_eventlistener();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
<!-- First Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="0" type="checkbox"> <label></label>
</div>
<!-- Second Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="2" type="checkbox"> <label></label>
</div>
<!-- Third Element -->
<div class="ui fitted slider checkbox comment">
<input data-status="3" type="checkbox"> <label></label>
</div>
<button class="button-action">Do Stuff</button>

How to trigger('click') on jquery tab's currently active tab

I have a tabed screen and want to trigger a click on the selected tab once the form is submitted and the return is valid. Here a part of the html:
<ul id="tabUL" class="tabs js-tabs same-height">
<li class="current">
<a class="tabLink" href="#tabProducts" data-url="/bla/bla">Products</a>
</li>
</ul>
My success command is :
success: function(data, textStatus, XMLHttpRequest) {
$('#tabUL').find('li.current a').trigger('click');
}
This seems not working... Any help is appreciated :) Regards Andrea
Try using the a[href=""] selector:
$('#tabUL a[href="#tabProducts"]').trigger('click');
I put together a jsfiddle demo to show it in action, and how to optionally hide the other tabs since often when I'm programmatically forcing tabs its to require missing mandatory information be entered on the initial tab before unlocking the other tabs...
Edit
Here is the contents of the jsfiddle:
HTML
<div id="tabs">
<ul>
<li>Address</li>
<li>Shipping</li>
<li>Parts</li>
<li>Datasheets</li>
</ul>
<div id="tab0">
<h1>This is the first tab (0)</h1>
</div>
<div id="tab1">
<h1>This is the second tab (1)</h1>
</div>
<div id="tab2">
<h1>This is the third tab (2)</h1>
</div>
<div id="tab3">
<h1>This is the fourth tab (3)</h1>
</div>
</div>
<br/>
Select the
<select id="tabSelect">
<option value="0">1st</option>
<option value="1">2nd</option>
<option value="2">3rd</option>
<option value="3">4th</option>
</select>Tab and
<input type="checkbox" id="tabHide" checked="checked" /> Lock the Others
jQuery
$(document).ready(function () {
$('#tabs').tabs();
$('#tabSelect').change(function () {
//pass empty array to unlock any locked tabs
$('#tabs').tabs({disabled: []}).find('a[href="#tab' + $(this).val() + '"]').trigger('click');
if ($('#tabHide').prop('checked')) {
//hide will be an array like [0,2,3]
var hide = Array();
$('#tabs li').not('.ui-tabs-active').each(function () {
hide.push($(this).index());
});
$('#tabs').tabs({disabled: hide});
}
});
});
If you want to reload the tab programmatically then i recommend use Jquery Tab API utility like below:
This makes first tab active and then activates second tab, quite simple and also raises the events that would be normally raised when you click directly.
$( "#myTabs" ).tabs( "option", "active", 0 );
$( "#myTabss" ).tabs( "option", "active", 1 );
Also you can catch tabs active event like below for performing any operations
$( "#myTabs" ).on( "tabsactivate", function( event, ui ) {
// your custom code on tab click
});
rather than trying to trigger the click event itself (which I believe is not possible to invoke a user event programatically in this context), I suggest that you trigger the function that has to be called on click event, you might want to look into triggerHandler

Categories