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

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.

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!

How to Console log the Entire HTML Form?

I'm trying to console log the entire form but the JavaScript Code is getting too long. Can anyone please help me how to follow DRY(Do not repeat Yourself), coz I have repeated a lot of code in my script tag
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName < /label> < input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input onclick="myFunction()" id="button" type="submit">
</li> </ul>
</form>
This is my Script tag. I want to follow DRY rules. I have tried saving the values to each separate variables.
<script>
var nameInput = document.getElementById('simple-input1');
document.querySelector('form.form').addEventListener('submit', function(e) {
//prevent the normal submission of the form
e.preventDefault();
console.log("Username: " + nameInput.value);
});
var nameInput1 = document.getElementById('simple-input2');
document.querySelector('form.form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log("Password: " + nameInput1.value);
});
</script>
You can get the form elements using document.querySelector('form.form').elements
document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
let x = document.querySelector('form.form').elements;
console.log("Username: ", x['userid'].value);
console.log("Password: ", x['pwd'].value);
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName</label>
<input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;">
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;">
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>
You could use FormData and pass the form element as a parameter. Then use FormData.entries() to get an iterator of all values
document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const entires = formData.entries();
for (var input of entires) {
console.log(input[0] + ': ' + input[1]);
}
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName </label> <input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>
Both your listeners are listening for the same thing - a submit. Make your code much simpler by merging them into a simplified listener, using template literals and newlines for the console.log():
document.querySelector("form.form").submit = function(e) {
e.preventDefault();
console.log(`Username: ${nameInput.value}\nPassword: ${nameInput1.value}`);
}

Insert e-mail address into input from div when link clicked

I have a wordpress web-site where guests can add posts from front-end.
In each post there are some <li> tags with certain text. One of <li> tags has an e-mail address. It looks like this <li class="E-mail">example#example.com</li>. In each post there is author's e-maill address and next to it there is a button SEND MESSAGE. When a guest clicks the SEND button a popup window appears with following fields: send to, your e-mail, your message... I want the e-mail address of author to be automatically added from <li> to the SEND TO field in popup window.
There is a list of added posts on a page. Each post is in the tag <article> and each article tag has an ID. Looks like this <article id="post-145">
Inside <article> tag there is <ul> with e-mail address.
Please, see the following code as an example. I need to paste email from li tag to the input tag in popup window.
<article id="post-145">
<div class="aside">
<ul>
<li class="name"> Mark </li>
<li class="phone-no"> 911 </li>
<li class="E-mail"> example#example.com — Send Message </li>
</ul>
</div>
</article>
<div class="popup-window">
<form>
Send to: <input type="text" value="example#example.com" /> Your e-mail: <input type="text" value="" /> Your message: <input type="text" value="" />
<input type="submit" value="SEND MESSAGE" />
</form>
</div>
How to do it using JS or maybe smth else?
Please, help. I am looking for the solution.
using jQuery for solution. Steps are below
extract email ids from li tags with the function
set emailid into popup window's email id field
have a look into code snippet.
function extractEmailId (text){
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
$('.popup-open-link').on("click", function(){
var emailid = extractEmailId( $('.E-mail').text()).join('\n');
$('#mailid').val( emailid );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article id="post-145">
<div class="aside">
<ul>
<li class="name"> Mark </li>
<li class="phone-no"> 911 </li>
<li class="E-mail"> example#example.com — Send Message </li>
</ul>
</div>
</article>
<div class="popup-window">
<form>
Send to: <input type="text" value="example#example.com" id="mailid" /> Your e-mail: <input type="text" value="" /> Your message: <input type="text" value="" />
<input type="submit" value="SEND MESSAGE" />
</form>
</div>
With the help of Jquery and CSS, you may use the following code to get the current <li>'s data-value.
And in html, set your data-value for each <li>, declare id for the textbox:
window.onload = function() {
$(".popup-open-link").click(function() {
txtSender.value = $(this).closest("li").attr('data-value');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article id="post-145">
<div class="aside">
<ul>
<li class="name">M1ark </li>
<li class="phone-no">1911 </li>
<li class="E-mail" data-value="1example#example.com">1example#example.com — <a class="popup-open-link">Send Message</a> </li>
</ul>
<ul>
<li class="name">Mark </li>
<li class="phone-no">911 </li>
<li class="E-mail" data-value="example#example.com">example#example.com — <a class="popup-open-link">Send Message</a> </li>
</ul>
</div>
</article>
<div class="popup-window">
<form>
Send to:
<input type="text" id="txtSender" value="" /> Your e-mail:
<input type="text" value="" /> Your message:
<input type="text" value="" />
<input type="submit" value="SEND MESSAGE" />
</form>
</div>
Vanilla JS Version
You don't need jQuery for something this simple.
Answer details included via comments.
<article id="post-145">
<div class="aside">
<ul>
<!-- BE SURE TO FIX YOUR `calss` TYPOS! -->
<li class="name"> Mark </li>
<li class="phone-no"> 911 </li>
<!--
Using `href="javascript:void(0)"` avoids unneccessary
uncertainties when using an anchor tag for this purpose.
-->
<li class="E-mail"> example#example.com —
<a href="javascript:void(0)" class="popup-open-link">
Send Message
</a>
</li>
</ul>
</div>
</article>
...
<!--
NOTE:
Corrected from `type="text"` to `type="email"`.
This will provide additional validation.
Also added the correct `<label>` elements accordingly,
and `name` properties.
It is best practice to manipulate and access DOM
form inputs via the `name` property, not `id`.
-->
<label for="send-to">Send to:</label>
<input name="send-to" type="email" value=""/>
<label>Your e-mail:</label>
<input type="email" value="" />
<label>Your message:</label>
<input type="text" value="" />
<input type="submit" value="SEND MESSAGE"/>
</form>
</div>
...
<!--
Other answers included waiting for a "onload" event.
This is unneccessary as long as you insert the script
*after* the `<article>`.
-->
<script type="text/javascript">
/*
encapsulates the JavaScript to avoid bugs
via conflicting code.
*/
;(function () {
function extractEmail (text) {
var emailRegex = /([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi;
return text.match(emailRegex)[0];
}
function populateMessageSendToFieldWithAuthorEmail () {
var authorEmailListItem = document.querySelector('.E-mail');
var messageForm = document.querySelector('.popup-window form');
messageForm['send-to'].value = extractEmail(
authorEmailListItem.innerText
);
}
function addListenerToTriggerElement () {
var triggerElement = document.querySelector('.popup-open-link');
triggerElement.addEventListener(
'click',
populateMessageSendToFieldWithAuthorEmail
);
}
addListenerToTriggerElement();
})();
</script>

Form submit with javascript and input required

I was trying to submit things using a div, HTML5, JavaScript. If I use a submit button the validator (required attribute in the inputs) works the button doesn't submit info. But if I use a div tag it doesn't validate and send the info. Any way to fix it? Or should I do the whole code to validate the info and stop the submit?
<form action="index.php" method="get" name='myform'>
<ul>
<li class="row">
<label class="labels" for="username">Username</label>
<input type="text" id="txtUser" required>
</li>
<li class="row">
<label class="labels" for="password">Password</label>
<input type="password" id="txtPass" required>
</li>
<li id="row2">
<div class="button">Submit</div>
<input type="submit">
</li>
</ul>
</form>
http://www.dropmocks.com/mCyfGJ
Im using the following code.
Javascript submit:
http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
HTML
enter code here
If you are submitting via JS then you need to call the form validation yourself. I don't see any issues in your post that would prevent the submit though (without validation). But here's a working example. Keep in mind that not all browsers support html5 validation.
function submitform() {
// Get first form element
var $form = $('form')[0];
// Check if valid using HTML5 checkValidity() builtin function
if ($form.checkValidity()) {
console.log('valid');
$form.submit();
}
else {
console.log('not valid');
}
return false
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="index.php" method="get" name='myform'>
<ul>
<li class="row">
<label class="labels" for="username">Username</label>
<input type="text" id="txtUser" name="sds" required>
</li>
<li class="row">
<label class="labels" for="password">Password</label>
<input type="password" id="txtPass" required>
</li>
<li id="row2">
<div class="button">Submit</div>
<input type="submit">
</li>
</ul>
</form>
I had a similiar problem and solved it this way.
<input type="submit" id="Guardar" name="Guardar" value="Guardar" onClick="if(this.form.checkValidity()){this.form.submit(); this.disabled=true; this.value='Enviando…';}else{this.form.checkValidity();}">
You can use a function to not handle it on element.

One form two actions depending on which button?

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.

Categories