Form hides on submit - javascript

On my form, you have to select an item in order for the form to show. The problem I'm running into is that on submit, it hides the form. How can I correct that?
This is my script:
<script>
$(document).ready(function () {
$(".orderForm").hide();
$(".choice").each(function () {
$(this).click(function () {
$(".orderForm").show();
});
});
});
</script>
Here's part of the html:
<form method="post" class="form-horizontal">
<div class="choiceContainer">
<#choicesSection><#choice id="2098885" class="choice">
<label>
<div align="left">
<h3 class="choiceName">
<#choiceSelectionRadioButton />
<#choiceName>148PKI</#choiceName>
</h3>
<div class="orderForm">
</div>
</div></div>
<div class="btn" align="center"><#selectedPaymentOptionSubmitButton label="Continue"
class="continue"/></div>
I updated the script too.

Use sessionStorage (or an appropriate polyfill script) to persist a variable across page loads. (Note sessionStorage serialized the data so when getting the value it will no longer be true but the string "true")
$(document).ready(function () {
if(!sessionStorage.formSubmitted)
$(".orderForm").hide();
//Reset it for possibly another form submission
sessionStorage.removeItem('formSubmitted');
$(".choice").each(function () {
$(this).click(function () {
$(".orderForm").show();
});
});
$("form.form-horizontal").submit(function(){
sessionStorage.formSubmitted = true;
});
});

Related

Submit button is not working. why?

The submit button is working when the function is defined on the same page. But it's not working when the action of the submit button is defined in separate JS file.
<form method="post">
<div id="sjfb">
<div id="form-fields">
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DisplayFor(model => model.controls);
#Html.DisplayFor(model => model.formEditor);
}
</div>
<button type="submit" id="submit" class="submit">Save Form</button>
</div>
</form>
// in separate .js File)
$("#sjfb submit").click(function () {
alert('Submit button is working');
}
I even tried the following methods:
1. document.getElementID('submit').onClick(function(){*some code*}
2. Giving a name to the function and calling it in onClick()
3. $(#sjfb #submit).click(function(){...})
4.$(#sjfb .submit).click(function(){...})
still not working. I can't find what is wrong with this.
You're missing the dot on submit class event handler.
$("#sjfb submit")
You should have:
$("#sjfb .submit")
The problem is in this snippet
$("#sjfb submit").click(function () {
alert('Submit button is working');
}
Just to make it clear you should change it as follows:
$(document).ready(function(){
$("#sjfb .submit").click(function () {
alert('Submit button is working');
});
});
Or as follows:
$(document).ready(function(){
$("#sjfb #submit").click(function () {
alert('Submit button is working');
});
});
since you've given class and id both as "submit" to your submit button. So you should add that to your js also.
Your entire code as tested on w3 is as follows:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sjfb .submit").click(function () {
alert('Submit button is working');
});
});
</script>
</head>
<body>
<form method="post">
<div id="sjfb">
<div id="form-fields">
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DisplayFor(model => model.controls);
#Html.DisplayFor(model => model.formEditor);
}
</div>
<button type="submit" id="submit" class="submit">Save Form</button>
</div>
</form>
</body>
</html>
if you load your javascript file before le dom content is loaded, then it can't bind the event on the button. try loading le js file a the end of the document, or you can add the event when the event $(window).on('load', fn) is fired
Replace your code with this
$(document).ready(function() {
$("form").submit(function () {
alert('Submit button is working');
});
});
Try with finding the element inside the div
$("#sjfb").find('button[type="submit"]').click(function (e){
console.log(this);
});
This code will find the button inside the id="sjfb" div and will call
the click function.

Ajax form in image slider

I am using the code below from superluminary's answer to this question jQuery AJAX submit form to ajaxify all the forms on my site.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(response) {
$(form).parent('.like-this').html("works");
$(form).parent('.dislike-this').html("works");
}).fail(function(response) {
console.log('Ajax form submit does not work!');
});
});
return this;
}
})(jQuery)
$(function() {
$('form[data-autosubmit]').autosubmit();
});
Then I add data-autosubmit to my form tag and the form submits using ajax.
E.g. <form action="like/post" method="post" data-autosubmit>
THE PROBLEM
In my image slider, which is based on this image slider, I have a form, which acts as a like button. The form works fine but the page reloads and the modal window closes on form submit. It does not use ajax, although I put data-autosubmit into the form tag.
The exact same form works fine (using ajax) at other places in my project.
THE SLIDER (the relevant part)
/*
* jQuery Slider Plugin
* Version : Am2_SimpleSlider.js
* author :amit & amar
*/
(function ($) {
jQuery.fn.Am2_SimpleSlider = function () {
//popup div
$div = $('<div class="product-gallery-popup"><div class="popup-overlay"></div><div class="product-popup-content"><div class="product-image"><img id="gallery-img" src="" alt="" /><div class="gallery-nav-btns"><a id="nav-btn-next" class="nav-btn next"></a><a id="nav-btn-prev" class="nav-btn prev"></a></div></div><div class="product-information"><p class="product-desc"></p><div class="clear"></div><hr><br><br><div class="like-image"><form action="" method="post" class="like-form" data-autosubmit></form><div class="liked"></div></div>X</div></div>').appendTo("body");
//on image click
$(this).click(function () {
$('.product-gallery-popup').fadeIn(500);
$('body').css({ 'overflow': 'hidden' });
$('.product-popup-content .product-image img').attr('src', $(this).find('img').attr('src'));
$('.product-popup-content .product-information p').html($(this).find('.image-description').html());
// In the like-image div is the form
$('.product-popup-content .product-information .like-image').html($(this).find('.like-image').html());
$Current = $(this);
$PreviousElm = $(this).prev();
$nextElm = $(this).next();
if ($PreviousElm.length === 0) { $('.nav-btn.prev').css({ 'display': 'none' }); }
else { $('.nav-btn.prev').css({ 'display': 'block' }); }
if ($nextElm.length === 0) { $('.nav-btn.next').css({ 'display': 'none' }); }
else { $('.nav-btn.next').css({ 'display': 'block' }); }
});
THE FORM
<!-- the image like button -->
<div class="like-image">
<?php if ($this->likedImages[$postImage->image_id]) { ?>
<!-- like the image -->
<div class="like-this">
<form action="<?= Config::get('URL');?>like/like_image" method="post" class="like-form" data-autosubmit>
<input type="hidden" name="image_id" value="<?= $postImage->image_id; ?>" />
<button type="submit" class="button like-button">Like</button>
</form>
</div><!-- /.like-this -->
<?php } else { ?>
<!-- dislike the image -->
<div class="dislike-this">
<form action="<?= Config::get('URL');?>like/unlike_image" method="post" class="like-form" data-autosubmit>
<input type="hidden" name="image_id" value="<?= $postImage->image_id; ?>" />
<button type="submit" class="button like-button">Dislike</button>
</form>
</div><!-- /.dislike-this-post -->
<?php } ?>
<div class="liked"></div>
</div><!-- /.like-image -->
Please let me know if you need to see any more code.
I would be very thankful for any kind of help!!
As I understood your code you need to add ajaxForm init.
Change this lines:
// In the like-image div is the form
$('.product-popup-content .product-information .like-image').html($(this).find('.like-image').html());
To this:
// In the like-image div is the form
var contentContainer = $('.product-popup-content .product-information .like-image');
contentContainer.html($(this).find('.like-image').html());
contentContainer.find('form').autosubmit();
Some explanation:
when you calling this code
$(function() {
$('form[data-autosubmit]').autosubmit();
});
selector 'form[data-autosubmit]' cant resolve your form since it not presented in document (form stored in variable). When you attaching form to document by setting html content to .like-image element, you must call autosubmit to initialize jQuery plugin on newly created form.
The reason it's not doing what you ask is because you havent told it to. Your javascript is a self invoking function that throws out a function, like a plugin. you would then need to use that function to tell it to submit the form.
$('form[data-autosubmit]').submit(e) {
$(this).autosubmit();
e.preventDefault(); //prevent actual form submission
}

how to call custom alert on dialog method of jquery on form submit?

I want to show a custom popup alert with dialog of jquery.
I have call function on form submit
<form name="form" method='post' action="user/purchase_user_tip" onSubmit="validateLogin();">
jquery code
<script type="text/javascript">
function validateLogin()
{
var session = 1;
if(session==1)
{
$('#dialog').dialog('open');
return false;
}
}
</script>
html dialog
<div id="dialog" title="Dialog Title" style="display:none"> Some text</div>
To make the #'dialog' id visible use:
$('#dialog').show();
To hide it again use:
$('#dialog').hide();
Another way is to use the jQuery UI Dialog as it is:
declare it (without display none)
open when needed
Moreover use the event prevent default and a different function definition:
function validateLogin(obj, e)
{
var session = 1;
if(session==1)
{
e.preventDefault();
$('#dialog').dialog('open');
}
}
$(function () {
$('#dialog').dialog({autoOpen: false});
});
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<form name="form" method='post' action="user/purchase_user_tip" onSubmit="validateLogin(this, event);">
<input type="submit" value="ClicMe">
</form>
<div id="dialog" title="Dialog Title"> Some text</div>
If you are looking to display the '#dialog' you should consider using this code
function validateLogin() {
var session = 1;
if (session == 1) {
$('#dialog').dialog('open');
return false;
}
}

simple append issue with jquery

I have a simple question. My JS code is like this, but when I try to add a new element or content to the <div>, it comes up then goes up quickly. I don't know why.
How can I avoid this?
<head>
$(document).ready(function () {
$('#mybtn').click(function () {
$('#main').append('<button id ="mm" onclick="myfun()">generate code my fun.</button>');
});
});
</head>
<body>
<form id="form1" runat="server">
<button id ="mybtn">generate code</button>
<div id="main"></div>
</form>
</body>
You should stop the button from Submitting the form by setting the button's type to be that of button.
Example :
<button type="button" id="mybtn">generate code</button>
The default type for a <button> element is submit. Which is causing your <FORM> tag to submit.
Try this:
$('#mybtn').click(function (e) {
e.preventDefault();
$('#main').append('<button id ="mm" onclick="myfun()">
generate code my fun </button>');
return false;
});
Try with:
$('#mybtn').click(function (event) {
event.preventDefault();
$('#main').append('<button id ="mm" onclick="myfun()"> generate code my fun </button>');
});
preventDefault : If this method is called, the default action of the event will not be triggered.

Display the last state of HTML display after clicking back

I have this problem let say I click an event (e.g. radio button 2) to show() div2 and hide() div1. After that I click a link to redirect to the next page.
Then I click back button (browser <-). Radio button 2 is checked, but the display is div1 instead of div2. Here is a sample source code. Could anyone help me if this can be fix.
<!-- test.php START -->
<div id="div_1" style="display: block;">
<p>First Paragraph</p>
</div>
<div id="div_2" style="display: none;">
<p>Second Paragraph</p>
</div>
<div>
<input type="radio" id="rdo1" name="radio" checked/>First
<input type="radio" id="rdo2" name="radio" />Second
</div>
<div>
Just to reload the page or go to other page
</div>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function() {
$("#rdo1").click(function () {
$("#div_1").show();
$("#div_2").hide();
});
$("#rdo2").click(function () {
$("#div_1").hide();
console.log('test');
$("#div_2").show();
});
});
</script>
<!-- test.php END-->
<!-- test1.php START -->
DISPLAY SOMETHING
<!-- test1.php END -->
Web is stateless and by default the browser does not remember any settings of the previous page.. SO when you press the back button it is just like a page refresh like you opened the default page with default HTML
This is the expected and default behaviour
If you want the behavior you are expecting then you need to cache the page or store the state , either in a session or a cookie..
You can on DOMReady check which radio input is selected.
$(document).ready(function() {
var ind = $('input[name=radio]:checked').index();
$('div[id^=div]').hide().eq(ind).show()
$("#rdo1").click(function () {
$("#div_1").show();
$("#div_2").hide();
});
$("#rdo2").click(function () {
$("#div_1").hide();
console.log('test');
$("#div_2").show();
});
})
You would have to save the state somehow, either server-side with ajax or form posts or via client-side with cookie or localStorage.
You can set cookies easily with the jquery-cookie plugin or you can use vanilla javascript to set localStorage like this quick example:
<!doctype html>
<meta charset="utf-8">
<title>html5 notepad</title>
<textarea></textarea>
<script>
var n = document.getElementsByTagName('textarea')[0];
n.onchange = function(){localStorage.setItem("n",n.value);}
n.value = localStorage.getItem("n");
</script>
if ($('#rdo1').attr('checked')){
$("#div_1").show();
$("#div_2").hide();
}
if ($('#rdo2').attr('checked')){
$("#div_1").hide();
$("#div_2").show();
}
$("#rdo1").click(function () {
$("#div_1").show();
$("#div_2").hide();
});
$("#rdo2").click(function () {
$("#div_1").hide();
console.log('test');
$("#div_2").show();
});​

Categories

Resources