After I submit form, below line opens a popup modal.
<input class="js__p_start" type="submit" value="submit" name="submit"/>
I want to open this popup from a JS function where I will check if form field is not empty then only call this popup modal, otherwise will give alert to fill the form field.
Any way I call call this popup using that class from another JS function.
In case you need source code, see the source code of http://www.hunt4flat.com
Here is my code:
<script>
$(document).ready(function(){
$("#hidden_form").submit(function(){
var mobile = $("#mobile").val();
var name = $("#name").val();
var dataString = 'mobile='+ mobile + '&name='+ name;
if(name=='')
{
alert("Please Enter your name");
}
else
{
$.ajax({
type: "POST",
url: "ritz.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
//I Want to call Popup here, so that popup will appear only after user properly entereed form fields
}
});
}
return false;
});
});
</script>
How to do it?
JS file is:
(function($) {
$.fn.simplePopup = function(event) {
var simplePopup = {
settings: {
hashtag: "#/",
url: "popup",
event: event || "click"
},
initialize: function(link) {
var popup = $(".js__popup");
var body = $(".js__p_body");
var close = $(".js__p_close");
var routePopup = simplePopup.settings.hashtag + simplePopup.settings.url;
var cssClasses = link[0].className;
if (cssClasses.indexOf(" ") >= 0) {
cssClasses = cssClasses.split(" ");
for (key in cssClasses) {
if (cssClasses[key].indexOf("js__p_") === 0) {
cssClasses = cssClasses[key]
}
};
}
var name = cssClasses.replace("js__p_", "");
// We redefine the variables if there is an additional popap
if (name !== "start") {
name = name.replace("_start", "_popup");
popup = $(".js__" + name);
routePopup = simplePopup.settings.hashtag + name;
};
link.on(simplePopup.settings.event, function() {
simplePopup.show(popup, body, routePopup);
return false;
});
$(window).on("load", function() {
simplePopup.hash(popup, body, routePopup);
});
body.on("click", function() {
simplePopup.hide(popup, body);
});
close.on("click", function() {
simplePopup.hide(popup, body);
return false;
});
$(window).keyup(function(e) {
if (e.keyCode === 27) {
simplePopup.hide(popup, body);
}
});
},
centering: function(popup) {
var marginLeft = -popup.width()/2;
return popup.css("margin-left", marginLeft);
},
show: function(popup, body, routePopup) {
simplePopup.centering(popup);
body.removeClass("js__fadeout");
popup.removeClass("js__slide_top");
location.hash = routePopup;
document.getElementById("menu_but").style.visibility = "hidden";
document.getElementById("toTop").style.visibility = "hidden";
document.getElementById("cbp-spmenu-s1").style.visibility = "hidden";
},
hide: function(popup, body) {
popup.addClass("js__slide_top");
body.addClass("js__fadeout");
location.hash = simplePopup.settings.hashtag;
document.getElementById("menu_but").style.visibility = "visible";
document.getElementById("toTop").style.visibility = "visible";
document.getElementById("cbp-spmenu-s1").style.visibility = "visible";
},
hash: function(popup, body, routePopup) {
if (location.hash === routePopup) {
simplePopup.show(popup, body, routePopup);
}
}
};
return this.each(function() {
var link = $(this);
simplePopup.initialize(link);
});
};
})(jQuery);
Using my library:
$.ajax({
type: "POST",
url: "ritz.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
//I Want to call Popup here, so that popup will appear only after user properly entereed form fields
var popup = new jPopup({
title: "<h2>Succes</h2>",
content: "<p>Form has been sent succesfully, results: "+result+"</p>",
buttons: [{
text: "Close"
}]
});
popup.open();
}
});
Library: https://github.com/seahorsepip/jPopup
You can do the same with a jquery ui dialog but jquery ui dialogs require too much js and aren't that great in my opinion :P
Related
I'm using this plugin to validate a tel html input https://github.com/jackocnr/intl-tel-input
I send the form through an ajax response and receive the html structure updated. When I set this html to the page, it loses the plugin instance and it's a normal tel input again, without the plugin instance attached to it. How do I call the previous instance to the new input received that it's technically the same?
// Call and set plugin instance
var inputRec = document.querySelector('#phone_number_rec');
var itiRecruiter = window.intlTelInput(inputRec, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
callback(countryCode);
});
},
utilsScript : base_url + '/public/assets/modules/intl-tel-input-master/build/js/utils.js',
});
// Send form through ajax
// Submit recruiter experience
$('body').on('submit', '.submit-individual-recruiter', function(e){
e.preventDefault(e);
var form = $(this);
var post_url = $(this).attr('action'); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
if ($(this)[0].checkValidity() === false) {
event.stopPropagation();
form.addClass('was-validated');
} else {
$(this).addClass('was-validated');
var responseState = false;
var jqxhr = $.ajax({
url : post_url,
type: 'post',
data : form_data,
}).done(function(response){
response = JSON.parse(response);
if(response.result == 'success'){
responseState = true;
iziToast.success({
message: response.message,
position: "topRight"
});
} else if(response.result == 'error'){
iziToast.error({
message: response.message,
position: "topRight"
});
}
});
jqxhr.always(function() {
if(responseState == true){
var $row = $('#recruiter-experience');
var url = base_url + '/get_info/experience';
$.post( url, function( response ) {
response = JSON.parse(response);
$row.html(response.recruiterView.data);
});
}
});
}
});
well you replaced the dom, so the element that u initialized the tel-validator is gone.
one thing u could do is wrap your initializer into a function so u can just call it again
function initializeTel() {
var inputRec = document.querySelector('#phone_number_rec');
var itiRecruiter = window.intlTelInput(inputRec, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
callback(countryCode);
});
},
utilsScript : base_url + '/public/assets/modules/intl-tel-input-master/build/js/utils.js',
});
}
// call it initially
initializeTel();
// and then after u received and parsed the response
initializeTel();
With this code, i only can send the form if i press the button.
How can i send it also, if i press the enter button when the cursor is in the keyword text input? For example, i type in what im searching for, and press enter.
$(document).ready(function(e) {
$('#preloader').hide();
$('#searchButton').click(function(e) {
e.preventDefault();
var keyword = $("input[name='keyword']").val();
var kereses_helye = $("select[name='kereses_helye']").val();
var kereses_rendezes = $("select[name='kereses_rendezes']").val();
var kereses_sorrend = $("select[name='kereses_sorrend']").val();
if (keyword != "") {
$.ajax({
type: 'POST',
url: 'files/get_keszlet.php',
data: {
keyword: keyword,
kereses_helye: kereses_helye,
kereses_rendezes: kereses_rendezes,
kereses_sorrend: kereses_sorrend
},
dataType: "html",
cache: false,
beforeSend: function() {
$('#preloader').show();
},
success: function(data) {
var result = $.trim(data);
$('#result').html(result);
},
complete: function() {
$('#preloader').hide();
}
});
} else {
alert("Nem adta meg, hogy mit keres.");
}
});
});
Use keypress event and check for correct key
const input = document.querySelector('your-input-field');
input.addEventListener('keypress', event => {
if (event.key === 'Enter') {
// your code goes here
}
});
As you said, the cursor would be in any input,
You can do with this jquery code:
$('.input').keypress(function (e) {
if (e.which == 13) { // 13 is the ASCII number of Enter key.
sendRequest(); // Calling your function if Enter is pressed.
return false;
}
});
Write you logic in different function and call that function on click event an on keypress event.
$(document).ready(function(e) {
$('#preloader').hide();
$('#searchButton').click(function(e) {
sendRequest();
});
$("input[name='keyword']").keypress(function(e) {
if (e.which == 13) sendRequest();
});
function sendRequest() {
e.preventDefault();
var keyword = $("input[name='keyword']").val();
var kereses_helye = $("select[name='kereses_helye']").val();
var kereses_rendezes = $("select[name='kereses_rendezes']").val();
var kereses_sorrend = $("select[name='kereses_sorrend']").val();
if (keyword != "") {
$.ajax({
type: 'POST',
url: 'files/get_keszlet.php',
data: {
keyword: keyword,
kereses_helye: kereses_helye,
kereses_rendezes: kereses_rendezes,
kereses_sorrend: kereses_sorrend
},
dataType: "html",
cache: false,
beforeSend: function() {
$('#preloader').show();
},
success: function(data) {
var result = $.trim(data);
$('#result').html(result);
},
complete: function() {
$('#preloader').hide();
}
});
} else {
alert("Nem adta meg, hogy mit keres.");
}
}
});
You have to use submit event in jquery :
<form id="search-form">
<input type="text" name="keyword"/>
<button type="submit">Search</button>
</form>
$('#search-form').submit(function(){
// Your code here
});
I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)
I am trying to craft an AJAX form to display a success/failure/share message via a Fancybox once a user submits their email address on a form. Currently, the code throws the response up to the top of the page.
I have attempted a few variations from other answers provided here here, and here on Stack Overflow, but to no avail, as upon insertion the entire form ceases to load.
My current init.js is as follows:
$("#form").submit(function(e){
e.preventDefault();
leSubmitLoader();
dataString = $("#form").serialize();
var templateURL = $('#templateURL').attr('value');
var blogURL = $('#blogURL').attr('value');
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json",
success:
function(data) {
$.fancybox(
'<p>Content of the box in HTML</p>',
{
padding:15,
closeBtn:true
}
);
function leSubmit(returning){
$.fancybox(
);
$('#form, #error, #presignup-content').hide();
$('#success').fadeIn(function(){
var successScroll = $('#signup-body').offset().top - 20;
$('html,body').animate({scrollTop:successScroll}, 300);
});
if (returning == true) {
$('#returninguser, #returninguserurl').show();
var refCode = data.returncode;
$('#returninguser span.user').text(data.email);
$('#returninguser span.clicks').text(data.clicks);
$('#returninguser span.conversions').text(data.conversions);
$('#returninguserurl input#returningcode').attr('value', blogURL + '/?ref=' + refCode);
} else {
$('#success-content, #newuser').show();
var refCode = data.code;
$('#newuser input#successcode').attr('value', blogURL + '/?ref=' + refCode);
if(data.pass_thru_error == "blocked"){
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html('AWeber Sync Error: Email Blocked.');
} else if (data.pass_thru_error.AWeberAPIException != undefined){
err = data.pass_thru_error.AWeberAPIException;
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html(err.type+': '+err.msg);
}
}
// Referral URL
var refUrl = blogURL + '/?ref=' + refCode;
// Twitter (note: refUrl might not show up in share box on localhost)
var tweetUrl = 'http://twitter.com/intent?url=' + encodeURIComponent(refUrl);
var tweetMessage = $('input#twitterMessage').attr('value');
$('#tweetblock').html('Tweet<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>');
// Facebook (note: won't work on localhost)
$("#fblikeblock").html('<div class="fb-like" data-ref="'+refCode+'" data-href="'+refUrl+'" data-send="false" data-width="75" data-show-faces="false" data-font="arial" data-layout="button_count"></div>');
// Google +
function renderPlusone() {
gapi.plusone.render('plusoneblock', {'href':refUrl, 'size':'tall', 'annotation':'none'});
}
renderPlusone();
// Tumblr
var tumblr_button = document.createElement("a");
tumblr_button.setAttribute("href", "http://www.tumblr.com/share/link?url=" + encodeURIComponent(refUrl) + "&name=" + encodeURIComponent(tumblr_link_name) + "&description=" + encodeURIComponent(tumblr_link_description));
tumblr_button.setAttribute("title", "Share on Tumblr");
tumblr_button.setAttribute("onclick", "window.open(this.href, 'tumblr', 'width=460,height=400'); return false;");
tumblr_button.setAttribute("style", "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('http://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
tumblr_button.innerHTML = "Share on Tumblr";
document.getElementById("tumblrblock").appendChild(tumblr_button);
// RinkedIn
$('#linkinblock').html('<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="'+refUrl+'"></script>');
}
if(data.email_check == "invalid") {
leSubmitLoaderStop();
$('#error').html('This email address is invalid.').fadeIn();
}
else if(data.required.length) {
leSubmitLoaderStop();
$('.error').hide();
$d = String(data.required).split(",");
$.each($d, function(k, v){
$("#" + v + ".error").fadeIn();
});
}
else {
if(data.reuser == "true") {
leSubmit(true);
FB.XFBML.parse(document.getElementById('fblikeblock'));
} else {
leSubmit(false);
FB.XFBML.parse(document.getElementById('fblikeblock'));
}
$('body').addClass('submission-success');
}
}
});
});
I am not trying to fix your code but why you don't use this ajax format to handle success/failure ?
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json"
}).done(function () {
//success
$.fancybox("success", {
// options
});
}).fail(function () {
//error
$.fancybox("failure", {
// options
});
}).always(function () {
// optional after ajax is completed
$.fancybox("else", {
// options
});
});
For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});