jQuery - Refresh Contents of a DIV - forms

I have a form in a jQuery popup on a webpage. The jQuery popup is a div named .vote-form and the form inside it has the name "#form".
When the form is submitted, the content inside the jQuery popup changes to a success message. I need to make it so that when the jQuery popup is closed, the success message is removed and the form is refreshed back to the original form, so that when the jQuery popup is opened again, the form is showing again and NOT the success message.
My feeble attempt to get this result involved refreshing the ENTIRE page when the jQuery popup is closed. This PARTLY has the desired result, but when the page is refreshed, most browsers get a popup asking if the user wants to resubmit the form content. I need to avoid this.
This was my code handling the closing of the .vote-form:
$('.vote-form-close').click(function(event) {
event.stopPropagation();
$(".vote-form").fadeOut("normal");
$("#the-lights").fadeTo("slow",0);
$("#the-lights").css({'display' : 'none'});
window.location.reload();
});
I suspect that its possible to refresh ONLY the div, and not the entire page, but I do not know how to accomplish it.
Can someone assist me?
EDIT: Based on one of the answers below, I modified my code. I also wanted to show the code used to open the form up too:
$('.vote').click(function() {
$(this).parent().find(".vote-form").fadeIn("normal");
$("#the-lights").css({'display' : 'block'});
$("#the-lights").fadeTo("slow",0.7);
});
$('.vote-form-close').click(function(event) {
event.stopPropagation();
$(".vote-form").fadeOut("normal");
$("#the-lights").fadeTo("slow",0);
$("#the-lights").css({'display' : 'none'});
$(".vote-form").load(window.location.href + " .vote-form-container");
});
Here is the problem - I have 3 forms on the page. When "vote-form-container" is loaded, its loading ALL THREE forms into the .vote-form box - how do I modify the code to only load the .vote-form-container that is part of the specific .vote-form - I suspect I have to use $(this) but I tried modifying the code to this and it didnt work:
$(".vote-form")(this).load(window.location.href + " .vote-form-container");
I am thinking I did it wrong.
EDIT 2: Now the "Close" button dosen't work after the form is reloaded the first time:
$('.vote').click(function() {
$(this).parent().find(".vote-form").fadeIn("normal");
$("#the-lights").css({'display' : 'block'});
$("#the-lights").fadeTo("slow",0.7);
});
$('.vote-form-close').click(function(event) {
event.stopPropagation();
$(".vote-form").fadeOut("normal");
$("#the-lights").fadeTo("slow",0);
$("#the-lights").css({'display' : 'none'});
var current_form = $(this).closest('.vote-form'),
index = $('.vote-form').index(current_form)
current_form.load(window.location.href + " .vote-form-container:eq(" + index + ")");
});

Don't reload the page but redirect your user:
window.location.href = window.location.href.toString()
Or load the new form with ajax:
$(".vote-form").load(window.location.href + " .vote-form");
For more information on the ajax approach see api.jquery.com/load/#loading-page-fragments
Update:
Using jQuery the index function you are able to replace only the current form.
// I asume your button is in the form
var current_form = $(this).closest('.vote-form'),
index = $('.vote-form').index(current_form)
current_form.load(window.location.href + " .vote-form:eq(" + index + ")");

... I need to make it so that when the jQuery popup is closed, the success message is removed and the form is refreshed back to the original form...
So, if I well understood:
$('.vote-form-close').click(function(event) {
event.stopPropagation();
var vf = $(".vote-form");
/* fadeout and remove inner content of the popup */
vf.fadeOut("normal", function() { vf.empty(); });
/* reset the form */
document.getElementById('form').reset();
...
});

Related

Squarespace + PayPal - custom form with fee added issue with displaying total

I'm helping with a Squarespace site and it has a custom form added in code on a particular page. The form collects the payer's info, then can enter any amount in the "Total to charge" field, then it is supposed to display the 2.7% fee. However, I can ONLY get the fee to display if I refresh the page (chrome, safari, either one). Click here to see the page...let me know
here is a snippet of code:
<script>
$(document).ready(function () {
var $amount = $('input[name="amount_1"]');
var $fee = $("#fee");
var $total = $("#total");
var $amount_2 = $("input[name='amount_2']");
var processing_fee = .027;
var isCurrency = function (inval) {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(inval)) {
return true;
}
return false;
};
$amount.on('input propertychange', function () {
if (isCurrency($amount.val())) {
var fee = ($amount.val() * processing_fee).toFixed(2);
var total = (Number(fee) + Number($amount.val())).toFixed(2);
$fee.text('$' + fee);
$amount_2.val(fee);
$total.text('$' + total);
}
});
$amount.on('blur', function () {
$amount.val($amount.val().replace("$", ""));
$amount.val(Number($amount.val()).toFixed(2));
if (!isCurrency($amount.val())) {
$amount.val("");
}
});
$("#paymentform").validate({
submitHandler: function (form) {
form.submit();
}
});
});
</script>
When a custom script only runs on page refresh, the cause is likely to be Squarespace's AJAX loading:
Occasionally, Ajax may conflict with embedded custom code or anchor
links. Ajax can also interfere with site analytics, logging hits on
the first page only.
Disabling AJAX is often a simple solution:
You can disable Ajax in the Style Editor, with some exceptions:
Ajax can't be disabled in Skye, Foundry, or Tudor.
Ajax can't be disabled on the blog landing page for Farro and Haute. If you uncheck Enable Ajax Loading in these templates, they
will still use Ajax to load the Blog Page.
To enable or disable Ajax:
In the Home Menu, click Design, and then click Style Editor.
Scroll down to Site: Loading.
Check or uncheck Enable Ajax Loading.
If you do not want to disable AJAX, then see "Option 2" here for how to write your code so that it will work on initial page load and on AJAX page loads.

Mapbox GL Popup .setDOMContent example

I'm trying to create a customized button to appear on a pop up which generates a dynamic link (a URL). I don't seem to be able to do this via the .setHTML because of the timing, can't bind a button to a function at runtime. So I thought I'd try the newish .setDOMContent
There's zero information online as to how this feature works. I'm wondering if anyone has an example of this where a button is added to the popup that can run a function and send data.
Here's my very poor attempt at setting this up.
This function creates the popup
function GameObjectPopup(myObject) {
var features = map.queryRenderedFeatures(myObject.point, {
layers: ['seed']
});
if (!features.length) {
return;
}
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
var popup = new mapboxgl.Popup()
.setLngLat(feature.geometry.coordinates)
.setHTML(ClickedGameObject(feature))
.setDOMContent(ClickedGameObject2(feature))
.addTo(map);
};
This function adds the html via the .setHTML
function ClickedGameObject(feature){
console.log("clicked on button");
var html = '';
html += "<div id='mapboxgl-popup'>";
html += "<h2>" + feature.properties.title + "</h2>";
html += "<p>" + feature.properties.description + "</p>";
html += "<button class='content' id='btn-collectobj' value='Collect'>";
html += "</div>";
return html;
}
This function wants to add the DOM content via the .setDOMContent
function ClickedGameObject2(feature){
document.getElementById('btn-collectobj').addEventListener('click', function()
{
console.log("clicked a button");
AddGameObjectToInventory(feature.geometry.coordinates);
});
}
I'm trying to pipe the variable from features.geometry.coordinates into the function AddGameObjectToInventory()
the error I'm getting when clicking on an object (so as popup is being generated)
Uncaught TypeError: Cannot read property 'addEventListener' of null
Popup#setHTML takes a string that represents some HTML content:
var str = "<h1>Hello, World!</h1>"
popup.setHTML(str);
while Popup#setDOMContent takes actual HTML nodes. i.e:
var h1 = document.createElement('h1');
h1.innerHTML="Hello, World";
popup.setDOMContent(h1);
both of those code snippets would result in identical Popup HTML contents. You wouldn't want to use both methods on a single popup because they are two different ways to do the same thing.
The problem in the code you shared is that you're trying to use the setDOMContent to add an event listener to your button, but you don't need to access the Popup object to add the event listener once the popup DOM content has been added to the map. Here is a working version of what I think you're trying to do: https://jsfiddle.net/h4j554sk/

TinyMCE 3 - textarea id which fired blur event

When a TinyMCE editor blur occurs, I am trying to find the element id (or name) of the textarea which fired the blur event. I also want the element id (or name) of the element which gains the focus, but that part should be similar.
I'm getting closer in being able to get the iframe id of the tinymce editor, but I've only got it working in Chrome and I'm sure there is a better way of doing it. I need this to work across different browsers and devices.
For example, this below code returns the iframe id in Chrome which is okay since the iframe id only appends a suffix of "_ifr" to my textarea element id. I would prefer the element id of the textarea, but it's okay if I need to remove the iframe suffix.
EDIT: I think it's more clear if I add a complete TinyMCE Fiddle (instead of the code below):
http://fiddle.tinymce.com/HIeaab/1
setup : function(ed) {
ed.onInit.add(function(ed) {
ed.pasteAsPlainText = true;
/* BEGIN: Added this to handle JS blur event */
/* example modified from: http://tehhosh.blogspot.com/2012/06/setting-focus-and-blur-event-for.html */
var dom = ed.dom,
doc = ed.getDoc(),
el = doc.content_editable ? ed.getBody() : (tinymce.isGecko ? doc : ed.getWin());
tinymce.dom.Event.add(el, 'blur', function(e) {
//console.log('blur');
var event = e || window.event;
var target = event.target || event.srcElement;
console.log(event);
console.log(target);
console.log(target.frameElement.id);
console.log('the above outputs the following iframe id which triggered the blur (but only in Chrome): ' + 'idPrimeraVista_ifr');
})
tinymce.dom.Event.add(el, 'focus', function(e) {
//console.log('focus');
})
/* END: Added this to handle JS blur event */
});
}
Maybe it's better to give a background of what I'm trying to accomplish:
We have multiple textareas on a form which we're trying to "grammarcheck" with software called "languagetool" (that uses TinyMCE version 3.5.6). Upon losing focus on a textarea, we would like to invoke the grammarcheck for the textarea that lost focus and then return the focus to where it's supposed to go after the grammar check.
I've struggled with this for quite some time, and would greatly appreciate any feedback (even if it's general advice for doing this differently).
Many Thanks!
Simplify
TinyMCE provides a property on the Editor object for getting the editor instance ID: Editor.id
It also seems overkill to check for doc.content_editable and tinyMCE.isGecko because Editor.getBody() allows for cross-browser compatible event binding already (I checked IE8-11, and latest versions of Firefox and Chrome).
Note: I actually found that the logic was failing to properly assign ed.getBody() to el in Internet Explorer, so it wasn't achieving the cross-browser functionality you need anyway.
Try the following simplified event bindings:
tinyMCE.init({
mode : "textareas",
setup : function (ed) {
ed.onInit.add(function (ed) {
/* onBlur */
tinymce.dom.Event.add(ed.getBody(), 'blur', function (e) {
console.log('Editor with ID "' + ed.id + '" has blur.');
});
/* onFocus */
tinymce.dom.Event.add(ed.getBody(), 'focus', function (e) {
console.log('Editor with ID "' + ed.id + '" has focus.');
});
});
}
});
…or see this working TinyMCE Fiddle »
Aside: Your Fiddle wasn't properly initializing the editors because the plugin was failing to load. Since you don't need the plugin for this example, I removed it from the Fiddle to get it working.

Add a jquery preloader on form submission

I am asynchronously submitting my form using jquery and AJAX . Refer the code below
$("#save_report").click(function()
{
$.ajax({
url : actionOfForm,
type : $('#custom_targeting_param_form').attr("method"),
data : $('#custom_targeting_param_form').serialize(),
success : function(){
alert('Report Saved successfully');
$("#showOrExportCustomTargetingReport").val('showReport');
}
});
return false;
});
I have got a link in my html with the id save_report and on clicking the link an Ajax call is being made to the URL which is passed as the actionOfForm variable as shown above.
Till this everything is fine. But now I want to get a preloader image/text like loading.. while the form submission is taking place in the background . And I want to show it in an alert box , not on my html ...
as i am a new user sorry for not able to post the image, but i hope i am comprehendable
Once the form submission is done , the preloader image will be gone and replaced with the success message alert.
Can you please help me with this?
i think you can have your image in a div..intially hide it..
<div id="imgDiv" style="display:none"><img src="/img.png"/><div>
then on click on your link(on AJAX call)..show this div on top of page(you have to use some css property for this).like this-
$("#save_report").click(function()
{
$('#imgDiv').show();// show your loading image
$.ajax({
url : actionOfForm,
type : $('#custom_targeting_param_form').attr("method"),
data : $('#custom_targeting_param_form').serialize(),
success : function(){
alert('Report Saved successfully');
$('#imgDiv').hide();// hide your image after successful call
$("#showOrExportCustomTargetingReport").val('showReport');
}
});
return false;
});

Preventing HTTP REQUEST on javascript DOM update

I am getting re-execution of imported js files upon a hitting a form button which calls a function to insert a DOM element into page ( in simulation to exe of an ajx callback function). The DOM insertion causes a page refresh which re-requests all files from server.
Nothing big on the function call:
var addFashionVideo = function() {
var nodeContainer = document.getElementById('vidList');
var mytitle = document.forms.addVideo.newVidName.value;
var addTextNode = document.createTextNode(mytitle);
var newLI = document.createElement('LI');
newLI.appendChild(addTextNode);
nodeContainer.appendChild(newLI);
return this;
};
TARGET DIV for DOM update code is :
<div id="ajParent" class="aj" style="width:325px;background-color:blue;color:white;">
<ul id="vidList">
<li>Watch Fashion Paris Video</li>
</ul>
</div>
I place an alert on this page and after the function attempts to insert the new LI
[ oddly the LI appears for a split second then disappears ] a page refresh is triggered
and my alert on the page re-executes.
// Perhaps Maybe I have a browser issue on this computer or I am just to new of a scripter
// to not see the problem...any comment appreciated.
The minute you hit submit on a form, the page will reload since you have made a GET request with the form. In order to stop the form from submitting you would have to make it return false on submit. e.g.
document.getElementById('formname').onsubmit = function {
return false;
};
You would have to make sure to disable form submission so the page doesn't reload, then you could run your ajax request on submission and do what you must on success in the ajax function.
I really doubt your dom insertion is causing the reload.