validation plugin starts to work only after the second run - javascript

Using modules and plugins jquery-validate.
But the plugin starts to work only after the second run of a modal window.
I can not understand why this is happening.
// Callback forms
(function(){
var app = {
init: function(){
this.setUpListeners();
},
setUpListeners: function(){
$(document).on('submit', 'form', this.submitForm);
$(document).on('keyup', 'input', this.removeError);
},
submitForm: function(e){
e.preventDefault();
var form = $(this),
btnSubmit = form.find('[type="submit"]');
if(app.validateForm(form) === false) return false;
btnSubmit.addClass('disabled');
var str = form.serialize();
$.ajax({
url: 'contacts.php',
type: 'post',
data: str
}).done(function(msg){
if(msg === "OK"){
var res = "<div class=\"alert alert-success\" role=\"alert\"> <strong>Well done!</strong> You successfully read this important alert message. </div>";
$(".fancybox").html(res);
setTimeout(function(){
$.fancybox.close();
}, 2000)
console.log('ok');
$(".fancybox").fancybox().trigger('click');
}else {
$(".fancybox").html(msg);
$(".fancybox").fancybox().trigger('click');
}
}).always(function(){
btnSubmit.removeAttr('disabled', '');
});
},
validateForm: function(form){
var inputs = form.find('input'),
valid = true;
form.validate({
invalidHandler: function(event, validator){
var errors = validator.numberOfInvalids();
if (errors) {
valid = false;
} else {
console.log('valide');
}
validator.focusInvalid();
}
});
return valid;
},
removeError: function(){
var $this = $(this),
formGroup = $this.closest('.form-group');
formGroup.removeClass('has-danger');
}
}
app.init();
})();
if($(".modalbox").length){
$(".modalbox").fancybox({
fitToView : false,
autoSize : false,
closeClick : false,
maxWidth : 502,
maxHeight : 444,
prevEffect : 'none',
nextEffect : 'none',
padding : 0,
margin : 50,
closeBtn : false,
helpers : {
overlay : {
css : {
'background' : 'rgba(0, 0, 0, 0.72)'
}
},
}
});
}
.callback-modal {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/additional-methods.js"></script>
</head>
<body>
<div class="wrap">
cb form
<div id="request" class="callback-modal">
<div class="callback-modal__inner">
<form class="callback__form" id="callbackForm">
<div class="form-row">
<input type="text" name="name" id="r-name" placeholder="Name" class="input" data-rule-required="true">
</div>
<div class="form-row">
<input type="text" name="phone" id="r-phone" placeholder="Phone" class="input" data-rule-required="true" data-rule-minlength="5">
</div>
<div class="form-row">
<input type="text" name="email" id="r-email" placeholder="E-mail" class="input" data-rule-required="true" data-rule-email="true">
</div>
<input type="submit" value="Send" class="btn btn__submit">
<div class="fancybox"></div>
</form>
</div>
</div>
</div>
</body>
</html>
This must be:
if the form does not pass validation, the submit button is disabled and not when sending data.
if a form is all right, it is submitted to.
How can fix this problem?

Related

jquery confirmation popup form with input values after clicking on submit

I am trying to create a form, after clicking on submit i should get a popup with entered values for confirmation with edit and submit buttons.
I see lots of examples but nothing is exact.
help is appreciated.
this is the code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/blitzer/jquery-ui-1.8.2.custom.css">
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
$(document).ready(function(){
$("#list").click(function() {
var cun = $("#list").val();
$.ajax({
type: "POST",
url: "http://localhost/prakash/popup form/view.php",
data: {'data':cun},
success: function(data){
//redirect to id using response
//window.location.replace("http://yoursite.com/products/" + response);
$('.display').html(data);
}
});
});
});
</script>
<script>
$(document).ready(function(){
$("#add").click(function() {
var cun = $("#dis").val();
$.ajax({
type: "POST",
url: "http://localhost/prakash/popup form/add.php",
data: {'data':cun},
success: function(data){
//redirect to id using response
//window.location.replace("http://yoursite.com/products/" + response);
$('.display').html(data);
}
});
});
});
</script>
<script>
$(function(){
// jQuery UI Dialog
$('#dialog').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Submit Form": function() {
document.testconfirmjq.submit();
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
$('form#testconfirmjq').submit(function(e){
e.preventDefault();
$("p#dialog-name").html($("input#name").val());
$('#dialog').dialog('open');
});
});
</script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>Welcome To My Homepage</h1>
</div>
<div align="center" data-role="main" class="ui-content">
Add New
Show List
</div>
<div class="display" align="center" display="inline">
<table id="dis" border="0">
<form id="testconfirmjq" method="POST" action="insert.php">
<tr><td>Name</td><td> <input type="text" name="name" id="name"></td></tr>
<tr><td>Age</td><td><input type="text" name="age" id="datepicker-13" size="30"></td></tr>
<tr><td>City</td><td> <input type="text" name="city"></td></tr>
<tr><td><input id="button" type="submit" name="send" value="Submit"></td></tr>
</form>
</table>
You entered your Name as:
If this is correct, click Submit Form.
To edit, click Cancel.
This code may be help you
function send(){
var name = document.getElementById('name').value;
var r = confirm(name);
if (r == true) {
//apply with your function(it will be excuted)
return true;
} else {
return false;
}
return false;
}
<form action="demo.php" onsubmit="return send()">
<input type="text" id="name">
<input type="button" value="send">
</form>

Get responses from php (SweetAlert)

I want to make form html look like this :
<script>
function name()
{
var name = $('#name').val();
var url_send = 'send.php';
$.ajax({
url : url_send,
data : 'name='+name,
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
}
</script>
<script src="assets/bootstrap-sweetalert.js"></script>
<script src="assets/sweetalert.js"></script>
<link rel="stylesheet" href="assets/sweet-alert.css">
<form action="#" method="post">
<label>Name</label>
<input type="text" name="name"><br>
<input type="submit" onclick="name();">
<div id="result"></div>
and this is send.php
<?php
$name = $_POST['name'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
And the problem is,how i show SweatAlert modal,when result of php is Success Sweatalert will show Success Modal.And when failed it will show Failed Modal ?
Now what must i edit to my script?
I hope you are expecting code with jquery ajax;
See the code below;
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<link rel="stylesheet" type="text/css" href="sweetalert-master/dist/sweetalert.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="sweetalert-master/dist/sweetalert.min.js"></script>
<script>
$(document).ready(function () {
$("#submit").on("click", function(e){
e.preventDefault();
var name_val = $("#name").val();
$.post( "send.php", {name_send:name_val}, function(data){
if (data == 'success'){
swal("Good job!", "Nice work!", "success");
return false;
}else{
swal("Here's a message!", "Please type a name");
}
});
});
});
</script>
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="name" id="name"><br>
<input type="submit" id="submit">
</form>
</body>
</html>
send.php
<?php
$name = $_POST['name_send'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
$.ajax({
url : url_send,
data : {name: name},
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
in your ajax code you placed data : 'name='+name, , please have a look at what i did , maybe that helps
Jquery ajax accepts object in data parameter data: {key:value}. In the question we are using string as a parameter to data of jquery ajax

Simple Backbone app not working

I wrote simple Backbone.js app from manual, but this does't work. Why?
It is a HTML-code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
<script src="source/jquery.js"></script>
<script src="source/underscore.js"></script>
<script src="source/backbone.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li>Start</li>
<li>Success</li>
<li>Error</li>
</ul>
</div>
<div id="start" class="block">
<div class="userplace">
<label>Enter name<input type="text" id="username"></label>
</div>
<div class="buttonplace">
<input type="button" id="button" value="Check">
</div>
</div>
<div id="error" class="block">
<p>Error - not found!</p>
</div>
<div id="success" class="block">
<p>Win!</p>
</div>
</body>
</html>
And it is a JS-code:
var Controller = Backbone.Router.extend({
routes: {
'': 'start',
'!/': 'start',
'!/error': 'error',
'!/success': 'success'
},
start: function() {
$('.block').hide();
$('#start').show();
},
error: function() {
$('.block').hide();
$('#error').show();
},
success: function() {
$('.block').hide();
$('#success').show();
},
});
var controller = new Controller();
var Start = Backbone.View.extend({
el: '#start',
events: {
'click #button': 'check'
},
check: function() {
console.log('WiN!');
if($("#username").val() == 'test') {
controller.navigate('success', true);
}
else {
controller.navigate('error', true);
}
}
});
var starter = new Start();
Backbone.history.start();
When I select point in menu, all work normal, but when I entered name into field and press button nothing happens. Event not activated. Why?
I think you're calling navigate incorrectly.
Try this:
controller.navigate('!/success', {trigger:true});
Documentation:
http://backbonejs.org/#Router-navigate

changePage is undefined

I am trying to build a simple app on phonegap and when i run the code i get an error in logcat as "Uncaught TypeError: Cannot call method 'changePage' of undefined". Here is my index.html and main.js. I am getting that error in the function of main.js.
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo</title>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.0rc2.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<script src="jquery.mobile/jquery.mobile-1.0rc2.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
<style>
body
{
background-color:#d0e4fe;
}
h1
{
color:Red;
text-align:center;
}
</style>
</head>
<body onload="init()">
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Welcome to Phonegap</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<script>
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"
$("#loginPage").live("pageinit", function(e) {
checkPreAuth();
});
</script>
</body>
</html>
main.js is here :
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
{
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
navigator.notification.alert("You entered a username and password");
handleLogin();
}
}
}
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var u = $("#username", form).val();
var p = $("#password", form).val();
var str1 = "bidray";
var str2 = "fivestars123";
var n1 = str1.localeCompare(u);
var n2 = str1.localeCompare(p);
if(u != '' && p!= '') {
$.post("http://www.coldfusionjedi.com/demos/2011/nov/10/service.cfc? method=login&returnformat=json", {username:u,password:p}, function(res) {
if(n1==0 && n2==0) {
$.mobile.changePage("some.html");
} else {
navigator.notification.alert("Your login failed", function() {});
}
$("#submitButton").removeAttr("disabled");
},"json");
} else {
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
The problem is with the last line of the main.js. The changePage is not getting defined.
Any help would be appreciated.
Thanks.

Cannot read property 'value' of null

I have spent probably an hour attempting to get this figured out... I keep getting this error no matter what I try:
Cannot read property 'value' of null
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<h1>Hello, world!</h1>
<div id="login_box"><form class="form-inline" action="JavaScript: login();" method="post">
<input type="text" class="input-small" id="login_username" name="username" placeholder="Username">
<input type="password" class="input-small" id="login_password" name="password" placeholder="Password">
<label class="checkbox"><input type="checkbox" id="login_autologin" name="autologin"> Remember me </label>
<button type="submit" class="btn" name="login">Sign in</button>
</form></div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/overall_js.js"></script>
</body>
</html>
and the related JS file (overall_js.js):
function login() {
$("#login_box").html("logging you in....");
console.log(document.getElementById("login_username").value);
$.post("user.php?mode=login", {
username : document.getElementById("login_username").value,
password : document.getElementById("login_password").value,
autologin : document.getElementById("login_autologin").value,
}).done(function(data) {
result = JSON.parse(data);
if (result.status == 3) {
$("#login_box").html(
"Welcome back, " + result.user_row.username + "!");
} else {
$("#login_box")
.html("You was not logged in: , " + result.error_msg);
}
});
}
Thanks if you can figure this out! I am also new to jQuery and JS so if anyone has any suggestions to make it more "Standard", any tips are appreciated!
This line
$("#login_box").html("logging you in....");
replaces the content of your <div>. You remove the form and all input elements...
See corrections needed below, lines 6 and 7:
function login() {
$("#login_box").append("logging you in....");
var u = $('#login_username').val();
var p = $('#login_password').val();
var al = $('#login_autologin').is(':checked');
console.log(u, p, al);
$.post("user.php?mode=login", {
username : u,
password : p,
autologin : al,
}).done(function(data) {
result = JSON.parse(data);
if (result.status == 3) {
$("#login_box").html(
"Welcome back, " + result.user_row.username + "!");
} else {
$("#login_box")
.html("You was not logged in: , " + result.error_msg);
}
});
}

Categories

Resources