Why does the html disappear? - javascript

I would like to insert <div><p>Test</p></div> in another DIV at the top. So I try
$(document).ready(function(){
$('form').live('submit', function(){
var aform = $(this);
$('#w').append('<div><p>Test</p></div>');
});
});
HTML looks like
<div id="w">
<div><p>Test</p></div>
</div>
When I do that, it gets inserted, but goes away right after.
Try click on the Save button in this example.
http://jsfiddle.net/Rv2w7/

Use prepend() and cancel the submit:
$(document).ready(function(){
$('form').live('submit', function(){
var aform = $(this);
$('#w').prepend('<div><p>Test</p></div>');
return false; //cancel `real` submit
});
});

The page gets reloaded on submit. That's why the dynamically inserted tag disappears.

You need to cancel the default action to prevent the form from submitting:
$(document).ready(function() {
$('form').live('submit', function() {
var aform = $(this);
$('#w').append('<div><p>Test</p></div>');
return false;
});
});
Updated example: http://jsfiddle.net/Rv2w7/2/
return false; or event.preventDefault() is required to prevent the default action with live().

Because your form gets submitted each time, you need to prevent the default action:
$(document).ready(function(){
$('form').live('submit', function(event){
var aform = $(this);
$('#w').append('<div><p>Test</p></div>');
event.preventDefault();
});
});

After you click the save button the page submits, that's why its 'going away'. That happens because modifications on the current HTML only last until the page changes or refreshes, because a new GET will be issued to the server and the unchanged version of the HTML will be retrieved, overwriting your changes.
To save something permanently to your HTML you will need to use a server-side programming language; make your program retrieve previously saved strings to a cookie or session; make your program load data from a database, etc.

Related

Text from user input variable not staying in div element

I am taking a variable from an HTML form element and trying to put it into a div to be displayed on the website whenever I click a button. However it shows up for a second then pops away.
I tried taking it out of the document.ready() block but that didn't work. When I put a string literal in the $(".output").html the same problem occurs as well. Similar questions like mine seem to be a syntax error, but I don't seem to have any I can find.
$(document).ready(function(){
$(".sub").on("click",function(){
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
});
});
Here is my site on codepen: http://codepen.io/arcjackson06/pen/NNeQvJ
Your <button> will submit the surrounding form. You need to use:
<button class="..." type="button"></button>
Which will prevent the form from submitting when clicked.
Alternative you can prevent the default click event, with:
$('.sub').on('click', function(event) {
event.preventDefault();
// ...
This should do the trick:
$(".sub").on("click",function(e)
{
e.preventDefault();
var searchstring = $("#searchfield").val();
$(".output").html(searchstring);
}
No need for any extra JavaScript.
Just give your button an attribute type="button" and that should take care of it.
The problem is a button's default type is submit so you are refreshing the page.
The issue is that the form on your page is submitting every time someone clicks that search button. To prevent that you need to use event.preventDefault:
$(".sub").on("click",function(event){
event.preventDefault();
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
When someone is clicking on , Its submitting the form and your page is getting reloaded. If you donot want to submit the form
You can try this.
$(document).ready(function(){
$(".sub").on("click",function( event ){
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
event.preventDefault(); // This will prevent the form submission
});
});
It's refreshing the form. That's why you don't see value. See updated codepen : http://codepen.io/anon/pen/vGwNJP
I added return false as follows:
$(document).ready(function(){
$(".sub").on("click",function(e){
var searchstring = $("#searchfield");
$("#output").html(searchstring.val());
return false;
// Or e.preventDefault();
});
});
Alternatively, you can add e.preventDefault(); as well.
As you are using form it would try to do forms default action i.e. submit.
Here you need to do event.preventDefault in onclick handler.

Common jQuery to disable submit buttons on all forms after HTML5 validation

Please pardon me if it is a basic thing, because I am a new learner of Javascript/jQuery. I have been trying to disable submit button to disable multiple submits. I have come across multiple solutions here as well, but all those used specific form name. But I wanted to apply a global solution for all forms on all pages so I dont have to write code on each page, so I put this in footer, so all pages have:
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
This code works on all the forms in all pages as I wanted, but if there are HTML5 required fields in form and form is submitted without them, of course notifications are popped but button still gets disabled. So, I tried with this:
$('input:submit').click(function(){
if ($(this).valid()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
But this does not work. Kindly help me so that jQuery only disables when all HTML5 validation is done. Thanks
Try this and let me know:
$('input:submit').click(function(){
if ($(this).closest("form").checkValidity()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
Ruprit, thank you for the tip. Your example did not work for me (in Firefox), but it helped me a lot.
Here is my working solution:
$(document).on("click", ".disable-after-click", function() {
var $this = $(this);
if ($this.closest("form")[0].checkValidity()) {
$this.attr("disabled", true);
$this.text("Saving...");
}
});
Since checkValidity() is not a jQuery function but a JavaScript function, you need to access the JavaScript element, not the jQuery object. That's the reason why there has to be [0] behind $this.closest("form").
With this code you only need to add a class="disable-after-click" to the button, input, link or whatever you need...
It is better to attach a handler to the submit event rather than a click event, because the submit event is only fired after validation is successful. (This saves you from having to check validity yourself.)
But note that if a submit button is disabled then any value they may hold is NOT submitted to the server. So we need to disable the inputs after form submission.
The question is compounded by the new HTML5 attribute form which allows associated inputs to be anywhere on the page as long as their form attribute matches a form ID.
This is the JQuery snippet that I use:
$(document).ready( function() {
$("form").on("submit", function(event) {
var $target = $(event.target);
var formId = $target.attr("id");
// let the submit values get submitted before we disable them
window.setTimeout(function() {
// disable all submits inside the form
$target.find("[type=submit]").prop("disabled", true);
// disable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", true);
}, 2); // 2ms
});
});
---[ WARNING ]---
While disabling submit buttons prevents multiple form submissions, the buttons have the unfortunate side effect of staying disabled should the user click the [Back] button.
Think about this scenario, the user edits some text, clicks submit (and get redirected to different page to view the edits), clicks back to edit some more, ... and ... they can't re-submit!
The solution is to (re-)enable the submit button on page load:
// re-enable the submit buttons should the user click back after a "Save & View"
$(document).ready( function() {
$("form").each(function() {
var $target = $(this);
var formId = $target.attr("id");
// enable all submits inside the form
$target.find("[type=submit]").prop("disabled", false);
// enable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", false);
});
});
Try this
`jQuery('input[type=submit]').click(function(){ return true;jQuery(this).prop('disabled','disabled');})`
run this code on successful validation of the form

jQuery click event first then follow url

I want to call a click event and then follow the href url.
HTML Link:
<a class="autoSave" href="?year=2013&week=42">←</a>
JS:
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('.submitForm').click(); //HTML Form that I'm wanting a submit to happen
window.location = $(this).attr('href');
});
});
The code above will just follow the url and not submit the form. If I omit the window.location call, the submit works.
You don't wait for the .click() event to be fully handled to call window.location.
You should serialize your form, post it by ajax (with .post() for instance), and then, in the callback of the .post(), change your page :
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
var serializedData = $('#yourForm').serialize(); //For example
$.post('your/path/to/form/validator', serializedData, function(){
window.location = $(this).attr('href');
});
});
});
You can't do a form submit without the browser trying to follow the form action. You need to use ajax to post your autosave data to your submit form and then do the window redirect when the ajax return successfully.
$('.autoSave').click(function(event){
event.preventDefault();
$.ajax({
url: "whatever your submitForm.click() file is",
type: "POST",
data: {
formField: theValue
anotherFormField: theValue,
},
success: function( data ) {
window.location = $(this).attr('href');
}
});
}
The problem is that the browser doesn't wait until the for m submission is done before it unloads the page and follows the link.
I'd recommend moving the location redirection to the end of your form submission:
$('.autoSave').on('click', function(event){
event.preventDefault();
$('.submitForm').triggerHandler('submit', [$(this).attr('href')]);
});
$('.submitForm').on('submit', function(event, url) {
// Do the thing
window.location = url;
})
Give your form an id and use the submit() function to submit it. Use a jQuery selector on the ID instead of a class, especially if you recycle the class you gave it.
HTML
<form id="submitForm">...</form>
Javascript
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('#submitForm').submit();
window.location = $(this).attr('href');
});
});
If your form is a standard form, the easiest thing to do is set a hidden input field value to the followup url:
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('#redirectUrl').val($(this).attr('href'));
$('.submitForm').click(); //HTML Form that I'm wanting a submit to happen
});
});
In this scenario, you will have to have full control of the server side and you will be able to test for that value and do a 301.
This is far from ideal. There are a lot of options, but almost all of them are hackish in order to double-post from a single event.

Submit a form using onclick event, but only allow once

I am both setting a form's action and submitting the form via the onclick event of a div:
<div class="action_button" onclick="document.forms['test'].action='url/to/action';document.forms['test'].submit()">
<span class="action_button_label">Save</span>
</div>
This works fine, but I'm wanting to use some code that conditionally checks for the 'Save' in the action_label_button, and only lets the submit() fire once. I'm trying to prevent multiple saves (which is yielding duplicate data in my app) from occurring.
// disable save buttons onclick (prevent multiple clicks of save buttons)
$('.action_button_label').one('click', function() {
// if the button is a save button
if($(this).html().indexOf('Save') != -1) {
// submit the parent form
$(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
$(this).parents('form').submit();
}
});
$('form').bind('submit', function() {
$(this).find('action_button').attr('onclick', '');
});
This code doesn't seem to work as I expected. I'm afraid I'm a bit out of my depth here, any pointers would be great.
Try replacing
$(this).find('action_button').attr('onclick', '');
with
$(this).find('.action_button').attr('onclick', '');
You should always handle multiple submits server side to ENSURE you don't get them. However you can hide the button-label to assist with this client side.
$('.action_button_label').one('click', function() {
// if the button is a save button
if($(this).html().indexOf('Save') != -1) {
// submit the parent form
$('.action_button_label').hide(); //ADD THIS
$(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
$(this).parents('form').submit();
}
});
$('form').bind('submit', function() {
$(this).find('action_button').attr('onclick', '');
});

Trouble adding success flag to onbeforeunload

having issues with onbeforeunload. I have a long form broken into segments via a jquery wizard plug in. I need to pop a confirm dialog if you hit back, refresh, close etc on any step but need it to NOT POP the confirm dialog on click of the submit button. had it working, or at least I thought, it doesn't now.
<script type="text/javascript">
var okToSubmit = false;
window.onbeforeunload = function() {
document.getElementById('Register').onclick = function() { okToSubmit = true; };
if(!okToSubmit) return "Using the browsers back button will cause you to lose all form data. Please use the Next and Back buttons on the form";
};
</script>
'Register' is the submit button ID. Please help!
The problem is that the onclick event handler will not be called prior to if(!okToSubmit). All you are doing when you say:
document.getElementById('Register').onclick = function() { okToSubmit = true; };
Is just setting up the event handler. You are not actually retrieving the value of okToSubmit.
One way to fix this might be to setup the onclick event handler before registering onbeforeunload.
Plain old JS syntax a little rusty, so here it is in jQuery if anyone ever needs it, this works, at least for a form submit button. Change method to get if it suits your needs
<script type="text/javascript">
$(document).ready(function(){
var action_is_post = false;
$("form").submit(function () {
action_is_post = true;
});
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (!action_is_post)
return 'Using the browsers back, refresh or close button will cause you to lose all form data. Please use the Next and Back buttons on the form.';
}
});
</script>

Categories