Modal box + checkbox + cookie - javascript

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

Related

bootbox confirm: form not submitted on enter key press

I'm using bootbox to show a custom form to the user. Afterwards that form is used to modify the UI. Everything works fine, if I press the "Ok" button in the bootbox dialog. Pressing the ENTER button without touching the form (all values on default) also works properly. But if I put focus on one of my input fields and then press enter, my page just resets as if I pressed F5.
Can this be fixed?
My code:
bootbox.confirm({
message: "<form id='newGameForm' action=''>\
Playlist ID: <br> \
<input type='text' name='playlistID' size='35'/><br>\
Ruleset: <br>\
<input type='radio' name='rules' value='classic' checked> Classic\
<input type='radio' name='rules' value='adv'> Advanced\
</form>",
callback: function (result) {
if (result) {
let newGameParams = $('#newGameForm').serializeArray().reduce(function (obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
initGame(newGameParams);
}
}
});
Edit: I found out that pressing enter while focusing the form is circumventing the bootbox's submit and instead uses the form's own submit. This adds ?playlistID=ABC123&rules=classic to the url and reloads the page. Can I somehow reroute the submit?
This isn't how the confirm helper is intended to be used - your use-case pretty much requires you to use the dialog helper. At a minimum, to make what you have probably work, you would need to capture the onsubmit event of the form you're inserting into the dialog.
Here's an example. I also moved your form out to a template script tag, since it makes the rest cleaner:
Template:
<script type="text/template" id="form-template">
<form id="newGameForm" action="">
Playlist ID: <br>
<input type="text" name="playlistID" size="35"><br>
Ruleset: <br>
<label><input type="radio" name="rules" value="classic" checked> Classic</label> <br>
<label><input type="radio" name="rules" value="adv"> Advanced</label> <br>
</form>
</script>
JavaScript:
var template = $('#form-template').html();
var $dialog = bootbox.confirm({
message: template,
callback: function (result) {
if (result) {
let newGameParams = $('#newGameForm').serializeArray().reduce(function (obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
initGame(newGameParams);
}
}
});
$dialog.on('shown.bs.modal', function(e){
var $form = $('#newGameForm');
$form.on('submit', functino(fe){
fe.preventDefault();
$dialog.find('.btn-primary').trigger('click');
});
});
This only works if you do not override the btn class on the confirm button, but as-is, basically triggers a click on the confirm button when the embedded form is submitted. This example hooks into the form's submit event on the shown.bs.modal event (that link is for Bootstrap 4, but the same event is available in Bootstrap 3).

Trigger click once when page is loaded

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');
}
});

Submit form only if at least one checkbox is checked

i'm triyng to validate a form.
In this form you've to choose at least one element by checkboxes, and I can't be sure about their quantity (it depends by elements number).
I need to enable the submit input if one or more checkboxes are checked, and disable it if there aren't any checkbox checked, how can I do?
Here's my code:
<form id="booking">
<input type="checkbox" name="room1" class="roomselect"/>
<input type="checkbox" name="room2" class="roomselect"/>
<input type="checkbox" name="room3" class="roomselect"/>
<input type="submit" value="Request" id="subm" />
</form>
//dom ready handler
jQuery(function ($) {
//form submit handler
$('#booking').submit(function (e) {
//check atleat 1 checkbox is checked
if (!$('.roomselect').is(':checked')) {
//prevent the default form submit if it is not checked
e.preventDefault();
}
})
})
You can use :checked selector along with .length to find checked checkbox count:
var len = $(".roomselect:checked").length;
if(len>0){
//more than one checkbox is checked
}
Demo
The :checked selector will Match all elements that are checked or selected.
You could try this
$("#subm").click(function(e){
if($(".roomselect:checked").length == 0){
e.preventDefault();
}
});
i suggest you to use "button" instead of "submit".
please follow this
HTML->
<form id="booking" action="https://www.google.co.in/search">
<input type="checkbox" value="facebook" name="q"/>
<input type="checkbox" value="gmail" name="q"/>
<input type="checkbox" value="stackoverflow" name="q"/>
<input type="button" value="Request" id="submit" />
$(function(){
$("#submit").click(function(e){
var number_of_checked_checkbox= $("input[name=q]:checked").length;
if(number_of_checked_checkbox==0){
alert("select any one");
}else{
$("#booking").submit();
}
});
});
Vanilla JavaScript equivalent of the jQuery way, using document.querySelector
if (document.querySelector('.roomselect:checked')) {
// somethings checked
}
Demo
The easiest method would be with javascript, fortunately someone's already done all the work here (with jQuery). All you'd need to do to adapt that example is to change #form_check to #booking.
Essentially what that example is doing is forcing itself before the submit action when it sees one is being tried for the form then it's searching inside the form element for any checkbox elements with a checked state and if it can't find any is sending a preventdefault to stop whatever the client/browser's default response to a submit action request would be or otherwise just sending as normal.
Also regarding the other answers, using === is more secure and returning false gives you some redundancy. Here's some discussion on what the return false adds.
Additionally don't use click() for this as you potentially run into use cases where you're technically submitting the form but aren't actually clicking it, like say when you hit enter
try this
var checked = false;
$(function(){
$('#subm').click(function(e){
checkall();
if(!checked){
e.preventDefault();
}
});
$('.roomselect').change(function(e){
checkall();
});
checkall();
});
function checkall()
{
checked = $('.roomselect:checked').length > 0;
$('#subm').prop('disabled',!checked);
}
$("#form_id").submit(function(e) {
var totalChecked = $('#div_id:input[type="checkbox"]:checked').length;
if(totalChecked < 1)
{
alert('Please select at least one checkbox before submit');
return false;
}
});

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
});
});

Javascript AJAX call fails in firefox when return false;

There are several questions similar to this but they don't appear to be the same so here it goes?
I have a website in which I have a login form. I want to use ajax to call a php function and while everything works fine in chrome. In firefox when I click the login button which which triggers the logIn() javascript function I get redirected to the javascript:logIn() page which is white and just says false. If I remove the return false in the logIn() method it appears to work fine.
<form method="post" id="loginform" action="javascript:logIn()">
<div>
<input type="text" value="Username..." name="username" id="username" onfocus="defaultInputUsername(this)" onblur="clearInputUsername(this)" />
<input type="text" value="Password..." name="passwordText" id="passwordText" onfocus="setPass()"/>
<input type="password" value="" name="password" id="password" onfocus="defaultInputPassword(this)" onblur="checkPass()" />
<input type="submit" id="submit" value="Login" name="Submit"/>
<span>Create Account</span>
</div>
</form>
Above is the form which calls the logIn() javascript method which is found below:
function logIn() {
var action = "check-login.php";
var form_data = {
username : $("#username").val(),
password : $("#password").val(),
is_ajax : 1
};
$.ajax({
type : "POST",
url : action,
data : form_data,
success : function(response) {
if(response != 'failed')
$("#loginform").slideUp('slow', function() {
$("#login_response").html('<ul id="usernav" class="sf-menu sf-js-enabled sf-shadow"><li><div id="message"></div><ul><li><span>View Profile</span></li> <li><span>Logout</span> </li></ul></li></ul>');
$("#message").html('<a id="userlink" href="#"><span>' + response + '</span></a>');
$("ul.sf-menu").superfish({
animation : {
height : 'show'
}, // slide-down effect without fade-in
delay : 800, // 1.2 second delay on mouseout
autoArrows : false
});
});
else {
$("#username").css("border", "2px red inset");
$("#password").css("border", "2px red inset");
}
}
});
return false;
}
If someone could tell me when it works in chrome and not firefox and if I should be using return false at all. That would be awesome.
Thank You!
This is very unconventional code so it's a bit difficult to answer fully.
To hack the thing together I would change your action= to an onsubmit=. "action" was not intended for this.
<form ...stuff... onsubmit="return logIn();">
The return false in an onsubmit will prevent the page from posting. Make sure you note that it's returning the result of logIn(), which in your case is always false.
You could also do:
onsubmit="logIn(); return false;"
and remove the return false from your logIn function.
Note: The ajax call is async by default.
Since you are already using jQuery, why not set the action-attribute to a page that logs in the user if user has JavaScript disabled, and then add some javascript that automatically binds the submit-button to use your logIn()-function
Something like this would probably work (haven't tested it, but it should work):
//When document is ready/loaded
$(document).ready(function () {
//Register click handler for submit-button with id "submit"
$("#submit").click(function(event) {
//call javascript and prevent postback
event.preventDefault();
logIn();
});
}
and your loginform could look something like this:
<form method="post" id="loginform" action="login-page-without-javascript.php">

Categories

Resources