Cannot read property 'settings' of undefined when I click submit button - javascript

I don't know why I received this error when I changed the code to php (from html). when the extension of the file is html, the code is working fine.
<?php?>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="css/manual.css">
<!-- Optional theme -->
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<title>Register</title>
</head>
<body>
<nav class="navbar navbar-default" id="navBar">
</nav>
<div class="full">
<div class="col-xs-12">
<!--Side Bar-->
<div class="col-xs-3" id="navSide">
</div>
<div class="col-xs-6" id="signUpForm">
<h1>Register Page</h1>
<form role="form" id="signUpForm">
<div class="form-group">
<div class="form-inline spacer-12">
<input type="text" class="form-control" name="userFirstname" placeholder="First Name">
<input type="text" class="form-control" name="userLastName" placeholder="Last Name">
</div>
</div>
<div class="form-group ">
<input type="text" class="form-control"
name="userEmail"
placeholder="Email">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="userPassword" placeholder="Password">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="confirmPassword" placeholder="Password">
</div>
<div class="form-group ">
<label> Birthday* </label>
<input type="date" class="form-control" name="userBirthday" placeholder="Birthday">
</div>
<input type="submit" class="btn btn-info spacer-12" style="clear:both" >
</form>
</div>
</div>
</div>
<script src="js/startup.js"></script>
<script src="js/signup.js"></script>
</body>
</html>
<?php?>
then this is my jquery validation code
$(document).ready(function(){
$('#signUpForm').validate({
errorElement: "span",
errorClass: "help-block",
rules:{
userFirstName:{
required: true
},
userLastName:{
required: true
},
userEmail:{
required: true
},
userPassword:{
required: true
},
confirmPassword:{
required: true
},
userBirthday:{
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error').addClass('red-border');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success').removeClass('red-border');
}
});
});
This code causes error when I click the submit button (JQuery Validate Uncaught TypeError: Cannot read property 'settings' of undefined )
But the error is temporary and will vanish in a while.

You defined two ids with same name, whereas id should be unique.
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
Try to remove id from <div class="col-xs-6" id="signUpForm">

If you use the rules() method, make sure to initialize the validation first.
var validator = $("#Form1").validate();
$('#field1').rules("add", {
min: 1
});

This error is normally caused by trying to validate an element that is not a form. In the OP's case, there are two elements with the same ID:
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
jQuery searches a page from top to bottom, and the first element it finds with this ID is not a form.
The Validator.element() function (for validating single elements) can also cause this error, if attempting to validate an element that is outside the form.

NOTE two things
1. Define the Jquery function
include the function of jQuery !
(function( $ ) {
//Start Script
//endscript/
})( jQuery );
Change the Form Id because it's doing conflict between Form Id and Div Id
<form role="form" id="signUpForm1"> // include 1 in previous form id
And put this id into script
$('#signUpForm1').validate({ // put the Id in the script
Hope Your Task will be successful.

To add a small detail here, I ran into the same problem with jQuery UI time picker, and it also was due to the id being non-unique.
In my case, it's because I was grabbing the parent element from a template - duplicating it for a pop-up window. As a result, the contents of the window all had duplicate ids.
My normal workaround for that was to replace this:
$('#foo').bar();
with this:
myPopupWindow.find('#foo').bar();
That works quite well for most things, but not for the time picker. For that one, I wound up doing this:
myPopupWindow.find('#foo').attr('id', 'foo_' + someUniqueTag);
myPopupWindow.find('#foo_' + someUniqueTag).timepicker();
where someUniqueTag is a record id, random number or some other distinct string. This solved it quite nicely for me.

Related

keep properties after jquery.load

I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question

Ajax form not submitting form rails

I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>
Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!

.click() function doesn't work javascript / jquery

UPDATE:
Somehow the just work fine after I tried it..
UPDATE
I'm using .click() function on my javascript, but it doesn't work.
Here is my JS code:
src="jquery.js";
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var institutionID, acadCareerID;
$(document).ready(function(){
getInstitution();
institutionID = $( "select#institution option:checked" ).val();
if(institutionID == null){
institutionID = 1;
}
getAcadCareerByInstitution(institutionID);
acadCareerID = $( "select#acadCareer option:checked" ).val();
if(acadCareerID == null){
acadCareerID = 1;
}
getPeriodByAcadCareerAndInstitution(acadCareerID);
getDepartmentByAcadCareer(acadCareerID);
$("select#institution").change(function(){
institutionID = $( "select#institution option:checked" ).val();
getAcadCareerByInstitution(institutionID);
})
$("select#acadCareer").change(function(){
acadCareerID = $( "select#acadCareer option:checked" ).val();
getPeriodByAcadCareerAndInstitution(acadCareerID);
getDepartmentByAcadCareer(acadCareerID);
})
$("div#search").click(function(){
alert("The paragraph was clicked.");
console.log("abc");
});
});
all functions like getInstituion(), getAcadCareerByInstitution(institutionID) etc are ajax call.
Here is my HTML code:
<form action="doInsertSchedule" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="institution">Institution</label>
<select name="institution" class="form-control" id="institution">
</select>
</div>
<div class="form-group">
<label for="acadCareer">Academic Career</label>
<select name="acadCareer" class="form-control" id="acadCareer">
</select>
</div>
<div class="form-group">
<label for="period">Period</label>
<select name="period" class="form-control" id="period">
</select>
</div>
<div class="form-group">
<label for="department">Department</label>
<select name="department" class="form-control" id="department">
</select>
</div>
<div class="form-group">
<label for="date">Deadline Date</label>
<input type="date" class="form-control" id="deadline" placeholder="Deadline Date" name="deadline">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<div id="search" class="btn btn-default">Search</div>
</form>
I already put jquery for my Master Layout (Laravel 5)
<head>
<link rel="stylesheet" type="text/css" href="{{url()}}/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{{url()}}/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{url()}}/js/tools.js"></script>
<script src="{{url()}}/js/bootstrap.min.js"></script>
<title>BINUS - #yield('title')</title>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
I want the Search Button / Div to do something when I click. I can't see what's wrong here.
I already tried <div> to <button> but it just will work like submit. I also already tried to put event.preventDefault() at my JS code, but it didn't work too.
Maybe you can try with event delegation...
$(document).ready(function(){
$("body").on("click", "#search", function(){
alert("The paragraph was clicked.");
console.log("abc");
});
});
You code works OK. You need to write the jquery library in the final, just before of </body>
...
<script type="text/javascript" src=".../jquery.js"></script>
</body>
Example it works ok!: Example Jsfiddle
<button type="submit" class="btn btn-default">Submit</button>
<div id="search" class="btn btn-default">Search</div>
This looks like it will render on the page as two buttons. Your ID here is attached to the div, not to the button, they should both appear to look like buttons providing bootstrap is loaded, but only the div with "search" as the content will do anything.
This is the only thing that appears odd, the only other problem is you are not loading your jquery as stated elsewhere.
I don't have the reputation to comment, but have you added a jquery library before your script?
Secondly, if you did and the items on the page are loaded after the document has loaded you will need to change your code up, for instance:
Give your form an id
<form action="doInsertSchedule" method="POST" enctype="multipart/form-data" id="postForm">
Then in your jquery script
<script>
$('#postForm').on('click', '#search', function(){
alert("The paragraph was clicked.");
console.log("abc");
});
</script>
The above will allow the javascript to run on items that are bought in after document load, however it is important you set it on a parent element that is avaiable at document load

jQuery Validate plugin doesn't work in CodeIgniter

I'm trying to use the jQuery Validate plugin in a view of a CodeIgniter project using exactly like a lot of examples Internet, but doesn't work at all! I used a lot of sugerences that I found here in StackOverflow and other sites, but doesn't work. Here is my code:
<script src="<?php echo base_url(); ?>js/jquery-validation-1.16.0/dist/jquery.validate.js"></script>
<body>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-6">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Ingresar nueva empresa</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form id="formIngEmpresa">
<!-- RESPUESTA DE FORMULARIO -->
<!-- FIN RESPUESTA DE FORMULARIO -->
<div class="box-body">
<div class="form-group">
<label for="usuario_login">Nombre o Razón Social de la empresa</label>
<input type="input" class="form-control" id="nm_rs_empresa" placeholder="Ingrese login">
</div>
<div class="form-group">
<label for="usuario_password">Rut empresa</label>
<input type="input" class="form-control" id="nr_rut_empresa" placeholder="rut">
</div>
<div class="form-group">
<label for="usuario_password2">Descripcion empresa</label>
<input type="text" class="form-control" id="nm_desc_empresa" placeholder="Password">
</div>
<div class="form-group">
<label for="usuario_nm_usuario">Rubro de la empresa</label>
<input type="input" class="form-control" id="nm_rubro" placeholder="Ingrese nombres">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Ingresar</button>
<button type="reset" class="btn btn-default">Cancelar</button>
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.row -->
</section>
</body>
<script>
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
alert($("#formIngEmpresa").validate().form());
$("#formIngEmpresa").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
nm_rs_empresa: "required",
nr_rut_empres: "required",
nm_desc_empresa: "required",
nm_rubro: "required"
},
// Specify validation error messages
messages: {
nm_rs_empresa: "Porfavor introducir nombre empresa",
nr_rut_empres: "Por favor introducir rut",
nm_desc_empresa: "Por favor introducir una Descripcion",
nm_rubro: "Elija el rubro de la empreesa",
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
$("#submit").click(function(){
$("#formIngEmpresa").submit();
return false;
});
});
</script>
jQuery Validate plugin doesn't work in CodeIgniter
Right, it doesn't. jQuery is JavaScript and it only works in the browser, while CodeIgniter only works on the server. In other words, your framework does not matter to JavaScript as long as you send the proper HTML markup to the browser.
Here's why you're having difficulties...
You must have a name attribute on every input considered for validation and these names must exactly match the names you used when you declared your rules. Even your code comments say the same thing!
rules: {
// The key name on the left side is the name attribute <-- READ HERE!!
// of an input field. Validation rules are defined
// on the right side
nm_rs_empresa: "required", // <- 'nm_rs_empresa' must match the 'name' attribute
....
The click handler could be bypassing the plugin. Since jQuery Validate automatically captures the click event of the submit button and fully takes care of the submission, you absolutely would not need any additional event handlers. Remove this entire click handler... it's not needed.
$("#submit").click(function() { // REMOVE THIS
$("#formIngEmpresa").submit(); // REMOVE THIS
return false; // REMOVE THIS
}); // REMOVE THIS
Working DEMO: jsfiddle.net/wtdhvtc7/
First update the ID of the form
Instead if this
<form id="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js">
put
<form id="formIngEmpresa">
This is your first mistake, the ID of form must match with the JQuery methods $("#formIngEmpres").validate() where formIngEmpres is the ID of the form.

javascript blocks form from submitting

I'm using Django with bootstrap3 and using twitter's typeahead.js to get autocomplete on my form.
the form:
**
<div id="top" class="jumbotron">
<div class="container">
<h1 align="center">Home</h1>
<h3>
<form align="center" action="/search/" method="get" role="form">
<input id="navPersonSearch" type="text" name="q" placeholder="Search for Actor/Actress" autocomplete="off">
</form>
</h3>
</div> <!-- /.container -->
</div> <!-- /.jumbotron -->
**
script that handles autocomplete:
<script type="text/javascript">
$(document).ready(function() {
$("#navPersonSearch").typeahead({
name: 'people',
remote: 'name_autocomplete/?q=%QUERY'
});
});
</script>
This form doesn't have a submit button, so you submit it with enter. Commenting out the script allows the form to submit, but with the script it doesn't.
This may be due to typeahead modifying the keypress events; I'm not sure as I haven't worked with it. But reattaching the event might solve your problem.
try something like this :
$(document).ready(function() {
$("#navPersonSearch").typeahead({
name: 'people',
remote: 'name_autocomplete/?q=%QUERY'
}).keydown(function(e) {
if (e.keyCode === 13) {
$("form").trigger('submit');
}
});
});

Categories

Resources