Trigger click once when page is loaded - javascript

I have a form in my page like so:
<form id="shipping" action="some-action-url" method="post">
<ul>
<li>
<input id="ship238280" name="method" value="238280|479435" type="radio" checked="checked">
<label for="ship238280">Transport (€0,00)</label>
</li>
<li>
<input id="ship292259" name="method" value="292259|580109" type="radio">
<label for="ship292259">Pick up (€0,00)</label>
</li>
</ul>
</form>
I'm using a SaaS platform so I have limited access to scripts and need to make use of what's actually available. So I'm looking for more of a workaround....
In above form I have checked the first option. To actually set the first shipping option I have to submit the form. Then in the system this option is set.
So I have a function that submits the form:
function sendform(){
var loader = $('.cart-loader');
var form = $('#shipping');
$(loader).show()
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(),
success: function(data) {
$(loader).hide()
//$(this).unbind()
}
});
}
And a click event for when I click one of the options:
$('#shipping input').on('click', function(){
sendform()
});
What I want now is to submit the form on page load. So I have created something like this:
$(function(){
$('#shipping input').each(function(){
if($(this).is(':checked')){
$(this).trigger('click') // or sendform()
}
});
});
What happens now is that the form keeps submitting because everytime the page reloads (after submit) it wants to submit again!
How can I work around this knowing that it needs to submit first to set the option?
I tried things like $(document).one('ready', function(){ or something like $(this).unbind() in ajax success function.
I'm a bit lost :) So any help greatly appreciated!!

Try something like this: https://jsfiddle.net/noidee/uvm6jw3b/
$(document).ready(function(){
if( localStorage.getItem('submited') !== '1' ){
$('#myform').submit();
localStorage.setItem('submited', '1');
}
});

Related

multiple submit buttons only first initializes javascript

I'm echoing the Submit Button as seen below in each row of a Table. When clicked the Submit Button the Javascript initializes and alert()'s the response. The issue is only the first Button works as intended and subsequent buttons redirect to foobar.php.
Submit Button:
<form name="savefilenote" id="savefilenote" method="post" action="forbidden-savefilenote.php?notetype=2">Note: <input id="filenote" name="filenote" type="text" value="'.$filenote.'"> <input id="filename" name="filename" type="hidden" value="'.$filename.'"> <input type="submit" value="Save"></form>
Javascript:
<script>
$(function(){
$('.savefilenote').on('submit', function(e){
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'), // <-- get method of form
url: $(this).attr('action'), // <-- get action of form
data: $(this).serialize(), // <-- serialize
beforeSend: function(){
$('#result').html('');
},
success: function(data){
$('#result').html(data);
if(data === "0") {
alert("foo");
}
if(data === "1") {
alert("bar");
}
}
});
});
});
</script>
Use a class instead of an id.
$("#savefilenote") can find only one instance of a button since and ID works for a specific element. If you change it to $(".savefilenote") and apply the same class to all buttons it should work.
id should be specific to a single element. Using the same id to identify multiple tags, you'll end up only affecting the first element in the body. If you want to associate a behavior to a group of elements, you'll need to use a class.

Refresh a specific class after post ajax Javascript

So after lot of researchs, I come here to request your help, there is my problem :
I have a comment system with multiple forms on a same page (I use FOSCommentBundle on Symfony). And I want to be able to post comments with Ajax (this part work, no problems) and refresh the comment section after the post is submitted (And i'm stuck on this part).
There is an example of code :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$(".comments").load(window.location.href + " .comments");
}
});
});
<form method="POST" class="postAjax" action="./comment/post/1">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="1">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<form method="POST" class="postAjax" action="./comment/post/2">
<input type="textarea" name="comment">
<input type="hidden" name="identifier" value="2">
<input type="submit">
</form>
<div class="comments">
<!-- Comments refreshed after post here -->
</div>
<!-- ... -->
I have tried lot of things, the function ".load" of JQuery but it load all the "comments" class and duplicate the comments in each class.
If someone have a solution... Thank you
First of all, in the provided code, your <form> tag lack an action attribute for your code to work properly.
Then, to answer your question, modify your controller action (the one saving your new comment) so that it return the informations of the submitted comment (json format is better). Then, transform the returned json into html code, and append the result to your comments <div>, for example :
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var element = $(this);
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(newCommentData){
/* do some process here to transform your newCommentData array into html code */
$(element).next(".comments").append(newCommentData);
}
});
});
Also, if you want it to be cleaner, you could have an hidden 'div', with the same model as a comment div, but with each content replaced by patterns ( ex : %commentTitle%, %commentBody% ). Then each time you post a new comment, you could get that hidden div, and replace patterns with your comment data. That way, if you change comment section structure later, the JS script will still work the same way, without adjustments needed.
Try this
$(document).on("submit", ".postAjax", function(e){
e.preventDefault();
$(this).LoadingOverlay("show");
data = $(this).serializeObject();
var $comment = $(this).next(".comments");
$.ajax({
url: $(this).attr('action'),
type: 'POST',
success:function(){
$comment.append("<div />");
$comment.last("div").load(window.location.href + " .comments");
}
});
});

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Calling jQuery search on tab click

I have a jQuery search script that uses tabs for the user to define which search type they want to use. However, when the user searches for something and then selects a new search type (clicks on a tab) they have to go to the text box and press enter to submit their query again.
I want to call a the search when the user clicks on the tab of their choice, without them having to resubmit the query. How can I do this? I hope you can understand what I'm trying to describe.
My current jQuery code is:
$(document).ready(function(){
$("[id^=t_]").click(function(){
t=this.id.replace("t_","");
$("[id^=t_]").removeClass("s");
$("#t_"+t).addClass("s");
return false
});
$("#t_search").click();
$("form").submit(function(event){
event.preventDefault();
if($("#s").val().length>0){
q=$("#s").val();
$.ajax({
type:"GET",
url:""+t+".php?q="+q,
dataType:"html",
success:function(c){
$("#r").html(c);
$("#r").show()
}
});
}
});
});
My current HTML code is:
<div id="n">
All
Images
Videos
News
</div>
<form action="search" method="get">
<input type="text" id="s" name="q" maxlength="2048" autocomplete="off">
</form>
<div id="r"></div>
submit the form when the tab is changed:
$("[id^=t_]").click(function(){
t=this.id.replace("t_","");
$("[id^=t_]").removeClass("s");
$("#t_"+t).addClass("s");
if ($("#s").val()!="") { // only when there's a search term
$("form").submit();
}
return false
});
Try something like this...
You've already done half of the task.
$(document).ready(function(){
$("[id^=t_]").click(function(){
t=this.id.replace("t_","");
$("[id^=t_]").removeClass("s");
$("#t_"+t).addClass("s");
q=$("#s").val();
if($("#s").val().length>0){
q=$("#s").val();
$.ajax({
type:"GET",
url:""+t+".php?q="+q,
dataType:"html",
success:function(c){
$("#r").html(c);
$("#r").show()
}
});
}
return false
});
});

Modal box + checkbox + cookie

I would like to achieve the following:
On homepage load, display modal box
Within modal box, display a form with a single mandatory checkbox
On checking the checkbox, hit submit and close the modal box, proceed to homepage
Remember this checkbox tick preference using a cookie
On a users return to the homepage, if they have checked the checkbox,
the modal box won't display
I've been getting somewhere with this:
http://dev.iceburg.net/jquery/jqModal
In that I can get the modal box displaying on page load, but I can't work out how to get the form to make the checkbox mandatory and close the box. I also don't know where to start when setting a cookie.
Any pointers would be much appreciated.
Thanks
EDIT: to include code:
Index.html - to display modal box on page load
$().ready(function() {
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
setTimeout($('#ex2').jqmShow(),2000);
});
2.html - modal box content loaded via ajax
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
<form action="" method="POST" onSubmit="return validate(form);" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
Load the jquery cookie plugin to allow to set/read cookies: http://plugins.jquery.com/project/cookie
then.. something like this below. Untested, but you get the idea
index.html:
$().ready(function() {
if (!$.cookie('agreed_to_terms'))
{
$('#ex2').jqm({modal: 'true', ajax: '2.html', trigger: 'a.ex2trigger' });
$('#ex2').jqmShow();
}
});
2.html:
$().ready(function()
{
$('#agreeFrm').submit(function(e)
{
e.preventDefault();
if ($(this).find('input[name=checkbox]').is(':checked'))
{
$.cookie('agreed_to_terms', '1', { path: '/', expires: 999999 });
$('#ex2').jqmHide();
}
});
});
<form id="agreeFrm" action="" method="POST" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
I used a JQuery plugin not long ago called SimpleModal
I was very impressed with how easy it was. On the modal I had multiple checkboxes and to carried the values of the checkboxes back to the page the modal was on after a submit button was hit.
All the info and demos are on the SimpleModal homepage
It works, finally!
I was missing the callback when the cookie exists and these tics '' around the value of the cookie.
Here is how it looks like. Please, let me know if there is some obvious mistake.
(many thanks for your support)
function confirm(msg,callback) {
$('#confirm')
.jqmShow()
.find('p.jqmConfirmMsg')
.html(msg)
.end()
.find(':submit:visible')
.click(function(){
if(this.value == 'Proceed'){
$.cookie("agreed_to_terms", '1', { expires : 1, path: '/' }); //set cookie, expires in 365 days
(typeof callback == 'string') ?
window.location.href = callback :
callback();
}
$('#confirm').jqmHide();
});
}
$().ready(function() {
$('#confirm').jqm({overlay: 88, modal: 'true', trigger: false});
// trigger a confirm whenever links of class alert are pressed.
$('a.confirm').click(function() {
if ($.cookie('agreed_to_terms') == '1'){window.location.href = callback =
callback()
//they already have cookie set
}else{
confirm('About to visit: '+this.href+' !',this.href);
}
return false;
});
});// JavaScript Document

Categories

Resources