One form two actions depending on which button? - javascript

I have two files, preview.php & save.php
<form id="create-template" class="form" action="" method="post">
<p class="_50">
<label for="t-name">Template name</label>
<input type="text" name="t-name" class="required"/>
</p>
<p class="_100">
<label for="t-html">Template HTML</label>
<textarea id="t-html" name="t-html" class="required" rows="10" cols="40"></textarea>
</p>
<div class="clear"></div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-template" href="javascript:void(0);">Clear</a></li>
</ul>
<ul class="actions-right">
<li><div id="preview"><input type="submit" class="button" value="Preview template" onclick="return false;"></div></li>
<li><input type="submit" class="button" value="Create template"></li>
</ul>
</div>
</form>
Current JS:
$("#preview").click(function() {
$.post('preview.php', {body:$('#t-html').val().replace(/\n/g,'<br />'), function (result) {
//maybe use .ajax instead?
//open preview.php in new window
});
});
How can I use the same form but have two different actions depending on what button one presses?
Preview template => preview.php => opens to a new tab
Create template => save.php => posts on same page

You can have a click event handler for both the button and attach simultaneous ajax call with each other.
and you can use javascript to open window in new tab.
window.open(<url>)

Try setting "target" attribute of the form based on what button was clicked.
Change your form to the following:
<form id="create-template" class="form" action="" method="post" target="_blank">
<p class="_50">
<label for="t-name">Template name</label>
<input type="text" name="t-name" class="required"/>
</p>
<p class="_100">
<label for="t-html">Template HTML</label>
<textarea id="t-html" name="t-html" class="required" rows="10" cols="40"></textarea>
</p>
<div class="clear"></div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-template" href="javascript:void(0);">Clear</a></li>
</ul>
<ul class="actions-right">
<li><input id="preview-form" type="submit" class="button" value="Preview template" /></li>
<li><input type="submit" id="submit-form" class="button" value="Create template" /></li>
</ul>
</div>
</form>​
And add this JavaScript:
$('#preview-form').click(function(ev) {
$('#create-template').attr('action', 'preview.php');
$('#create-template').attr('target', '_blank');
});
$('#submit-form').click(function(ev) {
$('#create-template').attr('action', 'submit.php');
$('#create-template').attr('target', '');
});
​
I haven't tested this across all browsers, so you might want to do that.

Related

Webpage loses interactivity with JavaScript when a form is submitted

I have a single page website that has three buttons (styled with jQuery Mobile) as a menu which, when clicked, show different content that is contained on hidden "div". However, on the main page I have a form connected to mysql which lets users join in, but when you fill the form and click the button "submit", the page "kind of reloads" and the header buttons don't work anymore. So, when form is submitted on main div, menu stops to work (it doesn't display and hide content anymore) Is there any solution to this?
(I've included a snippet but here the problem is not seen as I can't connect it to mysql).
function updateContent(hash) {
var newClass = hash.substring(1);
var newContent = $("." + newClass).html();
$("#content").html(newContent);
$("#content").css("display", "none");
}
if (window.location.hash) {
updateContent(window.location.hash);
}
$(".contentUpdate").click(function() {
updateContent($(this).attr("id"));
$("#content").fadeIn();
$(".contentUpdate").removeClass("ui-btn-active");
});
.hiddenContent {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div id="menu">
<div data-role="navbar">
<ul>
<li><a class="contentUpdate" id="#swim">Swim</a></li>
<li><a class="contentUpdate" id="#cycle">Cycle</a></li>
<li><a class="contentUpdate" id="#run">Run</a></li>
</ul>
</div>
<!-- /navbar -->
</div>
<div id="content">
FORM
<div id="joinForm">
<form method="post">
<label for="name">Name and Surname(s)</label>
<input type="text" id="name" placeholder="Adam Smith" value="" name="name" />
<label for="email">Email</label>
<input type="text" id="email" placeholder="example#esade.edu" value="" name="email" />
<label for="phone">Phone</label>
<input type="text" id="phone" placeholder="+34 671 542 893" value="" name="phone" />
<fieldset data-role="controlgroup">
<p>Choose the sports you're interested in:</p>
<input type="checkbox" id="swimming" name="swimming" value="" />
<label for="swimming">Swimming</label>
<input type="checkbox" id="cycling" name="cycling" value="" />
<label for="cycling">Cycling</label>
<input type="checkbox" id="running" name="running" value="" />      <label for="running">Running</label>
</fieldset>
<div align="right">
<button type="submit" class="ui-shadow ui-btn ui-corner-all ui-btn-inline" name="submit" id="submit" value="submit">Submit</button>
</div>
</form>
</div>
</div>
<div class="hiddenContent swim">
swim
</div>
<div class="hiddenContent cycle">
cycle
</div>
<div class="hiddenContent run">
run
</div>
Thank you!

Form that changes class attribute to active

I have a web page associated with 3 <li> and each has its own onclick() function. By default, one of them is active. Now I have a form, if this form is submitted I want it to take me to one of the other two <li>.
In other words, I want it to remove the active class from the default one, and add it to one of the other two. How can I do that?
HTML:
<div class="container">
<ul class="editor-nav">
<li id="content-w" class="en-nav active">1. Add Status</li>
<li id="setting-w" name="setting-w" class="en-nav">2. Upload Image</li>
<li id="cover-w" class="en-nav">3. Upload Video</li>
</ul>
</div>
<div class="be-large-post-align" id="firstdiv">
<form class="" action="work.php" method="post">
<textarea id="special" name="post" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitMe" class="buttons-navbar btn btn-primary" value="POST" /></form>
</div>
<div class="be-large-post-align" id="seconddiv" style="display:none;">
<form class="" action="work.php" method="post" enctype="multipart/form-data">
<!-- <label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" multiple="multiple" style="display:none"
onchange="$('#upload-file-info').html(this.files[0].name)">
Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span> -->
Select Image Files to Upload:
<input type="file" name="files[]" multiple>
<textarea id="special" name="post2" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitIt" class="buttons-navbar btn btn-primary" value="Upload" />
</form>
</div>
<div class="be-large-post-align" id="thirddiv" style="display:none;">this is working! </div>
JQuery:
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" > </script>
<script src = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"> </script>
<script type = "text/javascript" >
$("#setting-w").on("click", function() {
$("#firstdiv").fadeOut(1, function() {
$("#seconddiv").fadeIn(1, function() {});
$("#thirddiv").fadeOut(1, function() {});
});
});
$("#content-w").on("click", function() {
$("#seconddiv").fadeOut(0.1, function() {
$("#firstdiv").fadeIn(0.1, function() {});
$("#thirddiv").fadeOut(0.1, function() {});
});
});
$("#cover-w").on("click", function() {
$("#seconddiv").fadeOut(0.1, function() {
$("#firstdiv").fadeOut(0.1, function() {});
$("#thirddiv").fadeIn(0.1, function() {});
});
});
</script>
Use data attribute to fade your div.
$('.editor-nav li').click(function(e) {
$('.editor-nav li').removeClass('active');
var data = $(this).data('myval');
if (data == "2" || data == "3") {
$(this).addClass('active');
var tstDiv = data - 1;
$(this).attr('disabled', true);
$(document).find($('*[data-val="' + data + '"]')).fadeIn();
$(document).find($('*[data-val="' + tstDiv + '"]')).fadeOut();
}
});
.active {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container">
<ul class="editor-nav">
<li data-myval="1" id="content-w" class="en-nav active">1. Add Status</li>
<li data-myval="2" id="setting-w" name="setting-w" class="en-nav">2. Upload Image</li>
<li data-myval="3" id="cover-w" class="en-nav">3. Upload Video</li>
</ul>
</div>
<div data-val="1" class="be-large-post-align" id="firstdiv">
<form class="" action="work.php" method="post">
<textarea id="special" name="post" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitMe" class="buttons-navbar btn btn-primary" value="POST" /></form>
</div>
<div data-val="2" class="be-large-post-align" id="seconddiv" style="display:none;">
<form class="" action="work.php" method="post" enctype="multipart/form-data">
<!-- <label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" type="file" multiple="multiple" style="display:none"
onchange="$('#upload-file-info').html(this.files[0].name)">
Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span> -->
Select Image Files to Upload:
<input type="file" name="files[]" multiple>
<textarea id="special" name="post2" rows="10" cols="80" placeholder="What's on your mind, <?=$_SESSION['name']?>?"></textarea>
<input type="submit" name="submitIt" class="buttons-navbar btn btn-primary" value="Upload" />
</form>
</div>
<div data-val="3" class="be-large-post-align" id="thirddiv" style="display:none;">this is working! </div>
After page submit if your page is reloaded page loose state. So set your value when page submit like:
localStorage.setItem('key', 'your form Number')
Get localStorage when page load like:
var formID = localStorage.getItem('key');
After that check for null before add class:
if (localStorage.getItem("key") != null) {
(".editor-nav ul li").eq(formID ).addClass("active"); // Check this one on page load
}
You can use removeClass() and addClass() if you wish to add/remove any class based on their id.
Example:
$("#setting-w").on("click", function(){
$("#content-w").removeClass('active');
$("#cover-w").removeClass('active');
$("#setting-w").addClass('active');
}

I need to display jquery popup only once with a function onload

I need to display jquery popup only once with a function onload. This is my popup with a window.onload function delay and to addclass is-visible, however I'm looking to add a cookie function so the popup will only load once per browser or cache.
Any suggestions would be fantastic! - J query & html in code
jQuery(document).ready(function($){
window.onload = function (){
jQuery(".bts-popup").delay(1000).addClass('is-visible');
}
//open popup
jQuery('.bts-popup-trigger').on('click', function(event){
event.preventDefault();
jQuery('.bts-popup').addClass('is-visible');
});
//close popup
jQuery('.bts-popup').on('click', function(event){
if( jQuery(event.target).is('.bts-popup-close') || jQuery(event.target).is('.bts-popup') ) {
event.preventDefault();
jQuery(this).removeClass('is-visible');
}
});
//close popup when clicking the esc keyboard button
jQuery(document).keyup(function(event){
if(event.which=='27'){
jQuery('.bts-popup').removeClass('is-visible');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bts-popup" role="alert">
<div class="bts-popup-container">
<div id="contact-form">
<form method="post" action="">
<input type="hidden" name="form_uid" value="e880e632-8e7c-4b51-8928-b63cd1b6cdb5">
<ul>
<li class="namefield">
<input name="name" type="text" class="name" placeholder="Your Name">
</li>
<li class="emailfield">
<input name="submit_by" type="text" class="email-contact" placeholder="Your Email">
</li>
<li class="telfield">
<input name="telephone" type="text" class="phone" placeholder="Contact Number">
</li>
<li class="commentsfield">
<textarea name="comments" class="query" placeholder="How Can We Help?"></textarea>
</li>
<li>
</li>
<li>
<input name="submit-button" type="submit" value="Submit" class="submit">
<p class="gdpr-small">*By clicking ‘submit’ you are consenting to us replying, and storing your details. (see our privacy policy).</p>
</li>
</ul>
<input type="hidden" name="required" value="name,submit_by,telephone,comments">
<input type="hidden" name="data_order" value="name,submit_by,telephone,comments,marketing-opt-in">
<input type="HIDDEN" name="automessage" value="mymessage">
<input name="ok_url" type="hidden" value="">
<input name="not_ok_url" type="hidden" value="">
</form>
</div>
<i class="fa fa-times-circle"></i>
</div>
</div>
How to simple manage cookies, i think you can watch here: link
I think it's pretty simple (pseudo-code):
if (getCookie("popup") doesnt exist OR is set to 0)
showPopup();
setCookie("popup",1);
else
destroyPopup();
endif
You can use this simple way to handle multiple popoups too.
If you use PHP, you can use $_COOKIE instead of a javascript function.
Hope it helps.

jQuery show() and hide() for multiple links on page

I am coding a webpage that will have three forms for corresponding questions hidden in divs- I'm using a simple .accordion-toggle for this functionality in bootstrap's framework.
When a user chooses the 'Ask a question' button it toggles down (using .accordion-toggle) and a form appears- using hide() the 'Ask a question' link should disappear.
The form will have a Submit button to post the form, but also a cancel link- the cancel link should trigger the form to collapse(using bootstrap .collapse), simultaneously the 'Ask a question' button should reappear.
I'm able to get it working using the show() and hide() method in jQuery. However with three cancel buttons on the same page I'm not sure how to attach a unique identifier to each link to properly collapse the correct div.
The fiddle below is the closest solution thus far.
See #DanielAlmeida Fiddle
https://jsfiddle.net/ek57ao0y/
<div class='form form0'>
<ul>
<li><a href="#" class='showForm' data-target='.form1'>Show form 1</a></li>
<li><a href="#" class='showForm' data-target='.form2'>Show form 2</a></li>
<li><a href="#" class='showForm' data-target='.form3'>Show form 3</a></li>
<li><a href="#" class='showForm' data-target='.form4'>Show form 4</a></li>
</ul>
</div>
<div class='form form1'>
<h3>Form 1</h3>
<div>
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<p>
<a href="#" class='cancel' data-target='.form0'>Cancel</a>
</p>
</div>
<div class='form form2'>
<h3>Form 2</h3>
<div>
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<p>
<a href="#" class='cancel' data-target='.form0'>Cancel</a>
</p>
</div>
<div class='form form3'>
<h3>Form 3</h3>
<div>
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<p>
<a href="#" class='cancel' data-target='.form0'>Cancel</a>
</p>
</div>
<div class='form form4'>
<h3>Form 4</h3>
<div>
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<p>
<a href="#" class='cancel' data-target='.form0'>Cancel</a>
</p>
</div>
You can do this by changing a bit of your code around.. by making sure you are hiding and showing the correct element. The below should do the job for you.
$(function() {
$(".submit-collapse").click(function(){
$(".contact-form").show();
$(".submit-collapse").hide();
});
$(".cancel-link").click(function(){
$(".contact-form").hide();
$(".submit-collapse").show();
})
});
.contact-form{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-trigger top-spaced hidden-md hidden-sm hidden-xs">
<div class="panel panel-default no-border">
<div class="panel-heading">
<h4 class="drk-grey">
Have another question? <a class="accordion-toggle collapsed collapsed grn-btn full-window-btn submit-collapse" data-parent="#accordion" data-toggle="collapse" href="#question-about-app-process">Submit Your Question </a>
</h4>
</div>
<form class="contact-form" action="/mailers/faq_contact_us" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="L+9iNJ7+yKMBBIFsSv0nEzet6tit4bfxTaoUNbopARhIzoN/GL3fn40AaY1sV095jddz6fXzs0p20axPIfki+A==" />
<div class="spaced">
<label for="name">Name</label><input type="text" name="name" id="name" class="form-control" required="required" />
</div>
<div class="row spaced">
<div class="col-md-6">
<label for="email">Email</label><input type="email" name="email" id="email" class="form-control" required="required" email="true" />
</div>
<div class="col-md-6">
<label for="primary_phone">Phone</label><input type="tel" name="primary_phone" id="primary_phone" class="form-control" required="required" phone="true" />
</div>
</div>
<div class="spaced">
<label for="message">Message</label><textarea name="message" id="message" class="form-control" required="required" rows="10" maxLength="1000">
</textarea>
</div>
<div class="spaced">
<input type="submit" name="commit" value="Submit Question" class="btn btn-small text-center" /><a class="accordion-toggle collapsed collapsed cancel-link" data-parent="#accordion" data-toggle="collapse" href="#question-about-app-process">Cancel</a>
</div></form>
</div>
"I'm not sure how to attach a unique identifier to each link to properly collapse the correct div"
You can use the parent() function. Example: this code removes everything inside the parent div...where this link is:
<div>blablabla something Remove</div>
In your cause, you will not use "remove", call the colapse function instead.

Clear only specific fields in HTML form when submitting

I have the following HTML form code:
<div data-role="popup" id="-add" data-theme="c" class="ui-corner-all" data-dismissible="false" data-overlay-theme="a" style="min-width:550px;">
<div data-role="content"> Delete
<form id="item-form" action="#" formaction="process" data-ajax="false">
<input type="hidden" name="type" value="hidden1" />
<input type="hidden" name="how" value="hidden2" />
<input type="hidden" name="loc" value="hidden3" />
<input type="hidden" name="itemtype" value="hidden4" />
<div align="left">
<h3> Add</h3>
</div>
<div class="popup-hrule"></div>
<div class="ui-grid-a ui-responsive">
<div class="ui-block-a">
<label for="location_name">Name</label>
<input type="text" name="location_name" id="location_name" value="">
</div>
<div class="ui-block-b" data-schema="types">
<label for="type_name">Type</label>
<select name="type_name" id="type_name">
<option data-item=".textarea:name; .value:id; .repeat:true"></option>
</select>
</div>
<div class="ui-block-a">
<label for="address">Address</label>
<input type="text" name="address" id="address" value="">
</div>
<div class="ui-block-b">
<label for="city">City</label>
<input type="text" name="city" id="city" value="">
</div>
<div class="ui-block-a">
<label for="state">State</label>
<input type="text" name="state" id="state" value="">
</div>
<div class="ui-block-b">
<label for="zip">Postal</label>
<input type="number" name="zip" id="zip" value="">
</div>
<div class="ui-block-a">
<label for="_lat">Latitude</label>
<input type="number" name="_lat" id="_lat" value="">
</div>
<div class="ui-block-b">
<label for="_lon">Longitude</label>
<input type="number" name="_lon" id="_lon" value="">
</div>
</div> <a data-role="button" data-inline="true" onclick="$(this).closest('[data-role=popup]').popup('close');">Cancel</a>
<a data-role="button" data-inline="true" data-theme="a" onclick="$(this).closest('form').submit();$(this).closest('form').find('input').val('');$(this).closest('[data-role=popup]').popup('close')">Add</a>
</form>
</div>
</div>
Since this is an ADD form I would like to close the form and clear all the fields except for the hidden ones at the top which are flags that tell me what I have to do with the data. When I execute the code it clears all the data in the form including the hidden fields so the second time I can't add a new record.
A best approach for me would be to close the form completely so I don't have to erase the fields in the form which are going to get new data when I try to open it again.
You're clearing all input elements:
$(this).closest('form').find('input').val('');
If you want to clear only some of them, you need to target specifically the ones you want. For example, if you want to clear all non-hidden input elements:
$(this).closest('form').find('input[type!="hidden"]').val('');
Worst case would be that you have to turn this one line of code into a couple of lines of code to identify the elements you want. But as long as there's some jQuery-selectable pattern to identify the ones you want, that's what you need to do.
A best approach for me would be to close the form completely so I
don't have to erase the fields in the form which are going to get new
data when I try to open it again.
$("#item-form").remove();
If the hidden fields are populated from server, you can reset the form, so all form fields will be reset to value which were there during page reload.
$('#item-form')[0].reset();
The plain JS way of doing it
document.getElementById("item-form").reset();
Updated after discussion with OP
Cancel
function resetForm() {
$('#item-form')[0].reset();
$(this).closest('[data-role=popup]').popup(‌​'close');
}
Change this:
<a data-role="button" data-inline="true" data-theme="a" onclick="$(this).closest('form').submit();$(this).closest('form').find('input').val('');$(this).closest('[data-role=popup]').popup('close')">Add</a>
For this:
<a data-role="button" data-inline="true" data-theme="a" onclick="$(this).closest('form').submit();$(this).closest('form').find('input[type!=\'hidden\']').val('');$(this).closest('[data-role=popup]').popup('close')">Add</a>
So that you are selecting just those input elements with type not equal to hidden.

Categories