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>
Related
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')
I have my mainpage.aspx and then my mainDetails.ascx
/*As well as this javascript:*/
$(document).ready(function() {
$("#modal-close").click(function() {
$("#modal-content, #modal-background, #modal-close").toggleClass("active");
});
$("#keywordSelection").click(function() {
alert('hit');
});
});
/*mainDetails.ascx is an `asp:UpdatePanel` this contains the following javascript:*/
function jsModal() {
$("#keywordSearch").click(function() {
//alert('hi');
$("#modal-content, #modal-background, #modal-close").toggleClass("active");
//$("#modal-content").$("divTestVal").append.html
var html = $("#modal-content").next("#divTestVal").html();
alert(html);
});
}
<!-- mainpage.aspx is a web form that contains the following:-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modal-background"></div>
<div id="modal-content">
<input type="button" id="modal-close" value="Close Modal Window" />
<br />
<div id="divTestVal">
[Append Values Here!]
</div>
<br />
<input type="button" id="keywordSelection" value="Selector!" />
</div>
What I need is a way to populate and read the values from the modal. Right now the html variable is returning null.
How do a get the [Append Values Here!] value from the modal?
I found out a way of doing it.
in the mainDetail.ascx javascript I added the following:
$('#modal-content div').each(function (index) {
alert($(this).text());
$(this).html("updated text now");
});
Not only does this loop through each div in the modal window on the mainpage.aspx, but it also updates the text values in the div.
I am using an accordion in a dialog to go through different steps that the end user will need to do. Each step has a button or text box with a button. How can I get it so that when a user hits the enter key it activates the button associated with the active heading.
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<div id="accordion">
<h3 id="Step1">Step 1:</h3>
<div>
<p>
To get started click "Setup" and it will configure this spreadsheet for use with the Connected Groups Add-on.
</p>
<p><button id="Step1B" class="action" onclick="step1()">Setup</button></p>
</div>
<h3 id="Step2">Step 2</h3>
<div>
<p>
To get started enter the name of your first contact group below then click "Create".
</p>
<p><input type="text" id="gName">
<button id="Step2B" class="action" onclick="step2()">Create</button></p>
</div>
<h3 id="Step3">Done</h3>
<div>
<p><center>
Thank you for using Connected Groups. More information or help can be found:
</center>
</p>
<p><button id="thankYou" onclick="step3()">Close</button></p>
</div>
</div>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(function() {
$( "#accordion" ).accordion({
heightStyle: "content"
});
}); // run on launch
function step1(){
alert("Step1");
$('#Step2').click();
};
function step2(){
var tb = $("#gName").val();
alert("Step2: "+tb);
$('#Step3').click();
};
function step3(){
google.script.host.close();
};
</script>
How can I get it so that when a user hits the enter key it activates the button associated with the active heading?
First, we can catch keypress events for input elements. If the keypress is an 'enter' key, then we will dispatch a click() to the 'active' button. We'll store that in a global variable, window.actionButton.
$(':input').keyup(function (event) {
if (event.keyCode == 13) {
window.actionButton.click();
}
});
If we assume that each panel contains a single button with class='action', then we can keep track of the 'active' button.
window.actionButton = ui.newPanel.find(".action");
The activate event fires whenever a header (+ panel) gets selected. During the page load, we will bind a function to that action, and have it update window.actionButton.
activate: function (event, ui) {
window.actionButton = ui.newPanel.find(".action");
},
The workflow improves if we move the focus to highlight the intended action. Ideally, focus should go to the next input, whatever that is, but in this simple accordion it's sufficient to move to the appropriate button:
window.actionButton.focus();
Unfortunately, when running in Google Apps Script HtmlService, we can target a programmatic button click but cannot control focus: Cannot simply force focus on text input in stand-alone Google App using HtmlService? You'll find that the jsFiddle operates differently than when in HtmlService because of this.
Script
Working jsFiddle.
<div id="accordion">
<h3 id="Step1">Step 1:</h3>
<div>
<p>To get started click "Setup" and it will configure this spreadsheet for use with the Connected Groups Add-on.</p>
<p>
<input type="button" id="Step1B" class="action" value="Setup" />
</p>
</div>
<h3 id="Step2">Step 2</h3>
<div>
<p>To get started enter the name of your first contact group below then click "Create".</p>
<p>
<input type="text" id="gName" />
<button id="Step2B" class="action">Create</button>
</p>
</div>
<h3 id="Step3">Done</h3>
<div>
<p>
<center>Thank you for using Connected Groups. More information or help can be found:</center>
</p>
<p>
<button id="thankYou" class="action">Close</button>
</p>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
/**
* On document load, set up accordion & event handlers
*/
$(function() {
$("#accordion").accordion({
heightStyle: "content",
// Handle activate event by setting a new "actionButton",
// and putting it into focus.
activate: function (event, ui) {
//alert(ui.newPanel.attr('id'));
window.actionButton = ui.newPanel.find(".action");
window.actionButton.focus();
},
// Likewise for create event
// This doesn't set focus - why not?
create: function (event, ui) {
//alert(ui.panel.attr('id'));
window.actionButton = ui.panel.find(".action");
window.actionButton.focus();
}
});
// Click handlers, assigned upon load
$('#Step1B').click(function () {
alert("Step1");
});
$('#Step2B').click(function () {
var tb = $("#gName").val();
alert("Step2: " + tb);
});
$('#Step3').click(function () {
google.script.host.close();
});
// Setup keypress event handler for all inputs
// If 'enter' is pressed, click the current actionButton.
$(':input').keyup(function (event) {
if (event.keyCode == 13) {
window.actionButton.click();
}
});
});
</script>
I am working on a bootsrap3 template, which is Ajax based.
My index file has a leftside menu and a conent block middle of the page, every time I click on a subelement of this left menu, an Ajax laod will put the page content in this block(ajax-content).*
Any time I call any page, my URL normally looks something like this /index.php#page-one.php, except when the page contains form submission.
The Problem happens when I add an action attribute (acion="page-one.php") to my form tag.
After the form submission my URL turns to /page-one.php ;
consequently I get a white page containing the page-one.php elements whitout any CSS styling and of course no index-file's elements.
What is the correct and best way to come a cross this issue?
index.php:
<body>
<!--Start Container-->
<div id="main" class="container-fluid">
<div class="row">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li class="dropdown">
<a id="configuration" href="#" class="dropdown-toggle">
<i class="fa fa-gears"></i>
<span class="hidden-xs">Menu-element</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="page-one.php">Menu-Subelement-one</a></li>
<li><a class="ajax-link" href="page-wo.php">Menu-Subelement-two</a></li>
</ul>
</li>
</ul> <!-- end of main-menu-->
</div>
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img.gif" class="loader" alt="preloader"/>
</div>
<!--inside this div a short description/introduction(simple text inside a <p> tag) about the Menu-element will be shown-->
<div id="content-header"></div>
<!--inside this div the page content of the Menu-subelement will be shown-->
<div id="ajax-content"></div>
</div>
<!--End Content-->
</div>
</div>
<!--End Container-->
<script src="plugins/jquery/jquery-2.1.0.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugin/jquery.form.js"></script>
<script src="js/script.js"></script>
And here is my script.js:
//
// Function for load content from url and put in $('.ajax-content') block
//
function LoadAjaxContent(url){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: url,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
//////////////////////////////////////////////////////
document.ready
//////////////////////////////////////////////////////
$(document).ready(function () {
var ajax_url = location.hash.replace(/^#/, '');
if (ajax_url.length < 1) {
ajax_url = 'home.php';
}
LoadAjaxContent(ajax_url);
$('.main-menu').on('click', 'a', function (e) {
var parents = $(this).parents('li');
var li = $(this).closest('li.dropdown');
var another_items = $('.main-menu li').not(parents);
another_items.find('a').removeClass('active');
another_items.find('a').removeClass('active-parent');
if ($(this).hasClass('dropdown-toggle') || $(this).closest('li').find('ul').length == 0) {
$(this).addClass('active-parent');
var current = $(this).next();
if (current.is(':visible')) {
li.find("ul.dropdown-menu").slideUp('fast');
li.find("ul.dropdown-menu a").removeClass('active')
}
else {
another_items.find("ul.dropdown-menu").slideUp('fast');
current.slideDown('fast');
}
}
else {
if (li.find('a.dropdown-toggle').hasClass('active-parent')) {
var pre = $(this).closest('ul.dropdown-menu');
pre.find("li.dropdown").not($(this).closest('li')).find('ul.dropdown-menu').slideUp('fast');
}
}
if ($(this).hasClass('active') == false) {
$(this).parents("ul.dropdown-menu").find('a').removeClass('active');
$(this).addClass('active')
}
if ($(this).hasClass('ajax-link')) {
e.preventDefault();
if ($(this).hasClass('add-full')) {
$('#content').addClass('full-content');
}
else {
$('#content').removeClass('full-content');
}
var url = $(this).attr('href');
window.location.hash = url;
LoadAjaxContent(url);
}
if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
$('#formSubmit').ajaxForm();
});
page-one.php:
<!--some php code here-->
<form class="validateForm" id="formSubmit" action="page-one.php" method="get">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" />
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="submit" class="btn btn-primary btn-label-left">
<span><i class="fa fa-save"></i> Save</span>
</button>
</div>
</div>
</form>
Thanks!
I had the same issue to solve for the intranet I work on.
For me, the good way to do this is to avoid using submit method and use instead an input button with a js function to send the form data.
In my case, I did this:
<!-- At the top of my webpage -->
<script language='Javascript'>
function loadingAjax(div_id,user,date1,date2)
{
$("#"+div_id).html('<br><center><img src="images/loading.gif"><br><br><font color="#006699" face="arial" size="4"><b>Loading data<br>VPlease wait ...</b></font></center>');
$.ajax({
type: "POST",
url: "activities.php?USER="+user+"&DATE1="+date1+"&DATE2="+date2,
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<!-- And here is my form -->
<form id='date_form'>
<input type='text' id='user'><input type='text' id='date1'><input type='text' id='date2'>
<input type='button' onclick="loadingAjax('myDiv',document.getElementById('user').value,document.getElementById('date1').value,document.getElementById('date2').value);">
</form>
This allow to send your form in a separate DIV without having to show to everyone your URL.
MORE: you can even use this function to manage your left side menu selection so that your URL would stay '/index.php' all the time.
Hope this help
Regards
Nico
How do you want to submit the form, using ajax?
If you want to use ajax, you should cancel the default action like you do with your links using e.preventDefault();. Post the javascript that handles the form submit if you need help with that.
If you want to post to page-one.php without using ajax, you could add a header() redirect after the php code that processes the form to redirect to the page that you would like to show after the form gets submitted.
As you are loading content by ajax,
You can post content to page-one.php and redirect user to it's previous page. But it will be difficult manage and show error, success, notification message like form validation errors etc.
Another and I think best solution is to use ajax form submission
I'm working on 'add a link' functionality. For that I'm using Modal plugin from Twitter Boostrap JS. On the main page there's only the 'link' field to fill, when a user clicks 'add link' button, a modal pops up, and the user sees the complete form to fill 3 fields: link, title, tags. However, I want 1) the link field to be pre-filled with the value from the previous step AND 2) the title field is pre-filled with the title of the url.
I can do each of these separately, but I can't do both. In fact, the code below pre-fills the link field leaving title field empty. If I uncomment the AJAX part and add 'onClick="sendRequest()', then the code prefills the title field by executing the php script 'savePostAjax.php' which given the url echoes the title. However, in that case the link field is not filled. I guess, Bootstrap events somehow interfere with AJAX I wrote. One approach I tried is to get the url title in JavaScript, didn't work. How would you go about solving this problem of pre-filling BOTH link and title of the form in the modal dialog? Thanks!
<html>
<head>
<title>Example</title>
<script src="scripts/jquery.min.js"></script>
<script src="scripts/bootstrap-modal.js"></script>
<link rel="stylesheet" href="scripts/bootstrap.min.css">
<link rel="stylesheet" href="main.css" />
<!-- AJAX
<script type="text/javascript" src="ajaxwebform/prototype.js"></script>
<script type="text/javascript">
function sendRequest() {
new Ajax.Request("savePostAjax.php",
{
method: 'post',
parameters: 'linkURL='+$F('linkURL'),
onComplete: showResponse
});
}
function showResponse(req){
$('show-title').value= req.responseText;
}
</script>
AJAX ENDS -->
<script type="text/javascript">
$(document).ready(function()
{
$('#modal-from-dom').bind('show',function()
{
$(".modal-body #wall-post").val($("#linkURL").val());
});
});
</script>
</head>
<body>
<!-- The Modal Dialog -->
<div id="modal-from-dom" class="modal hide fade">
<div class="modal-header">
×
<h3>Add Link</h3>
</div>
<div class="modal-body">
<!-- onsubmit='return false;' -->
<form id='post-on-wall' method='POST' action='savePost.php' enctype='multipart/form-data' >
<div>
<input id='show-title' class='label-inline' name='title' type='text' size='100'>
</div>
<div>
<input id='wall-post' class='label-inline' name='linkURL' type='text' size='100'>
</div>
<div>
<input id='link-field' class='label-inline' name='topics' type='text' size='100' placeholder='topics'>
</div>
</form>
</div>
<div class="modal-footer">
Add Link
</div>
</div>
<!-- Enf of The Modal Dialog -->
<div class="container">
<div class="wall-post">
<input id='linkURL' class='label-inline' name='linkURL' type='text' size='100' autocomplete='off'>
<button data-controls-modal="modal-from-dom" data-backdrop="true" data-keyboard="true" class="btn">Add Link</button>
<!-- onClick="sendRequest()" -->
</div>
</div>
</body>
The reason it doesn't work is because you've included prototype and jquery, both of which try to occupy $. You can easily get around this by using jQuery in noConflict mode but I'd recommend ditching prototype completely as it doesn't make sense to use two libraries in that situation.
I haven't actually run this, but it should be what you need. Of course before actually using it you'll want to add a little spinner indicating that the ajax request is being made etc.
jQuery(document).ready(function($) {
function setTitle(url) {
$.post("savePostAjax.php", { linkURL: $('#linkURL').val() },
function(resp) {
$('show-title').val= resp;
});
};
$('#modal-from-dom').bind('show',function() {
var linkURL = $('#linkURL').val();
$('.modal-body #wall-post').val(linkURL);
setTitle(linkURL);
});
});