Implementing jQuery function - javascript

I have been trying to implement some JavaScript that would disable a submit button until all fields were filled. I found a great here: Disabling submit button until all fields have values. Hristo provided a link that does exactly what I need here: http://jsfiddle.net/qKG5F/641/.
My problem is that when I try to put together a full "minimum working example" I am completely stumped. I'm sure there's some minor aspect that I'm missing but here's what I've come up with:
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to https://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to https://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
</script>
</head>
<body>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="text" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="text" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<div id="test">
</div>
</body>
I simply copied/pasted and added in what I thought would be necessary to make the page work but my submit button remains permanently disabled. What simple part am I missing to make this work??
Thanks!

You have to surround it with an onload function:
$(window).load(function(){
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
});
If you look at the source of the jsFiddle, you'll see it got wrapped the same way.

I tested this on my system, works with your own version of jquery, as well as code with a little change and wrapping javascript in document.ready().
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
});
</script>
</head>
<body>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="text" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="text" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br />
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
<div id="test">
</div>
</body>
</html>

Your original js is an immediately-invoked function expression. Here's a link explaining that pattern:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
You defined an anonymous function and then immediately called it. By the time your html page had loaded, the script had already run. As others correctly answered, you need to instead wait for all the DOM elements to load before executing the script.
While
$(window).load(function(){};
works, you should probably use the jQuery version of this:
$(document).ready(function(){ };
For one, it's the jQuery idiom, and for another, $(window).load fires at a later time, where as $(document).ready() fires as soon as all DOM elements are available; not as soon as all assets (possibly large) are loaded.
Source: window.onload vs $(document).ready()

If you place the JavaScript (the entire script element) at the end of the page, right before the closing body tag, it should work. This is because the JavaScript needs to be run after the DOM is built. By placing your script after the page is loaded (and then immediately invoking it as you are doing), the document will be ready and it should work.
Working example: http://jsfiddle.net/NgEHg/

Related

required and button click javascript validation function not work?

I m applying two validation but both are not work
required validatation not work on input attribute
function validatation() not work
signup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="signup.js"></script>
<script type="text/javascript">
function validatation() {
debugger
if (document.PersonalInform.txtfname.value == "") {
debugger
alert("Please provide your first name!");
document.PersonalInform.Name.focus();
return false;
}
}
</script>
</head>
<body>
<form id="txtPersonalInformation" name="PersonalInform" onsubmit="return (validatation());">
<h1>Personal Information</h1>
First Name:<input id="txtfname" name="txtfname" type="text" /><br/>
Middle Name:<input id="txtmname" name="txtmname" type="text" /><br/>
Last Name:<input id="txtlname" name="txtlname" type="text" /><br/>
<input id="btnnext" type="button" value="Next" />
</form>
</body>
</html>
OR
Below Validation Also Not Work
First Name:<input id="txtfname" name="txtfname" type="text" required /><br/>
signup.js
$(document).ready(function () {
$('#btnnext').click(function (event) {
$("#txtPersonalInformation").load("ContactInformation.html");
});
});
I add this line in web.config file
web.config
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
</appSettings>
I want to perform this javascript function validation but not work?
function validatation()
Here's what you want. You weren't submitting you form, as noted by Mendrika.
HTML Form:
<script src="https://code.jquery.com/jquery-3.4.1.min.js"> type="text/javascript"></script>
<form id="some-form" action="some-url" onsubmit="return validate()">
<label for="first-name">First Name:</label>
<input id="first-name" name="first-name" type="text"><br>
<label for="last-name">Last Name:</label>
<input id="last-name" name="last-name" type="text"><br>
<input id="btn-submit" type="submit" value="Submit">
</form>
JS Sample Validate function
function validate() {
if ($("#first-name").val() === "") {
alert("Provide a first name");
$("#first-name").focus();
return false;
}
if ($("#last-name").val() === "") {
alert("Provide a last name");
$("#last-name").focus();
return false;
}
return true;
}
https://codepen.io/el-sa-mu-el/pen/QWjVGvb
Note, this is not good code, but it works. You should read more about basics of JS and form validation.
Some other observations:
Your form is missing the action=" " tag which actually POSTs the data to some URL. Where is your data going?
You are mixing vanilla Java Script and JQuery. Use JQuery for DOM access if you already included it, with the $ symbol.
You have a signup.js function but also include a Javascript function in the <script> tags. You can move the validate() function into the signup.js
Better form validation with JQuery:
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
The reason nothing works is because your form is never submitted.
You just need to change the next button type to submit.
<input id="btnnext" type="submit" value="Next"/>

Javascript | Simple Form Validation Wont Work

I have been working on this really simple login, where all i want to do is say, if the password is "apple" and password is "123" then link me to another page when i click submit button.
I gave up on the submit button linking portion but i still don't understand why my code won't register, everything looks right to me
<!DOCTYPE html>
<html>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="Username" value=""/>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="button" name="submit" value="Login" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var user = document.loginForm.username.value;
return user;
var pass = document.loginForm.password.value;
return pass;
if ( (user=="apple") && (pass=="123") ) {
document.write("It worked");
} else {
document.write("Wrong Password");
}
}
</script>
</body>
</html>
Suggestions:
return keyword will exit the function, so the code after return won't be reached. To remove the two 'return' statement is the first step.
document.write will clear the page after document is loaded. You probably need alert function
try using document.getElementById/getElementByName (which is better) instead of document.loginForm...
It is also better to put onsubmit in the form tag (fired after type=submit button is clicked) instead of onclick event for button.
It is better to put Javascript inside the HTML head tag.
Below is a much better/working version:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
if ( (user=="apple") && (pass=="123") ) {
alert("It worked");
return true;
} else {
alert("Wrong password");
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit='javascript:return validate()'>
<input type="text" id="username" placeholder="Username" value=""/>
<input type="password" id="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
</body>
</html>

How to validate a form for all browsers including mobile browsers

I have a website http://www.yaseennikah.com/MyRegister.php. I need to validate the form on the client side. I used javascript code, but it is not working in some mobile browsers. I saw a jquery code here http://jsfiddle.net/WF2J9/16/. But I don't know to add jquery ul. So can any one complete the code please.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>form validation</title>
</head>
<body>
<form action="page1.php" method="post" class="a">
Name : <input type="text" class="text" name="name" id="name" /> <br/>
Address : <input type="text" class="text" name="address" id="address /><br/>
email : <input type="text" class="text" name="email" id="email" /> <br/>
<button id="submit" name="submit">submit</button>
</form>
<script>
$('#submit').on('click', function() {
valid = true;
if (valid && $('#name').val() == '') {
alert ("please enter your name");
valid = false;
}
if (valid && $('#address').val() == '') {
alert ("please enter your address");
valid = false;
}
return valid;
});
</script>
</body>
</html>
You can add jQuery to your web page using their official CDNs Add this to the head of your web page <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
And you can test if jQuery was loaded correctly using this code
if($) {
alert("jQuery loaded");
} else {
alert("jQuery not loaded");
}
Edit:
Here is my version of the validation script (now should be working) and don't forget to remove the trim() function if you don't want it.
Edit 2:
If you want to do this without jQuery, you can use html's automatic form validation example. But this is not supported in ie 9 and earlier.
Or you can try this (Rewritten jQuery code from above to pure js and a second way of form validation).
Validate the form on server's side too !!!

How to validate a php form with java script, that is on everypage of my site

The problem i'm having is Im trying to get the contact.php to validate a contact form that is now in the bottom of every page in my site. It worked great with just validating one page and having a hard URL to take them back to. the troubleing code is this.
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['HTTP_REFERER'].$report);
}else{$report='noerror';}
Ive also tryed this:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['PHP_SELF'].$report);
}else{$report='noerror';}
This is the original code that worked for one page:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header('Location:estimate_page.php?'.$report);
}else{$report='noerror';}
I could just make a new "contact.php" page for every page that has the form in the footer, but thats stupid if i can just make this work. Any ideas
You are thinking in the right direction with javascript/jQuery -- it will allow you to catch the invalid fields before submitting / changing pages. Much better user experience. Only submit when fields are validated.
Here is a link for how to do simple field validation testing with jQuery:
jsFiddle Demo
HTML:
One: <input type="text" id="f1"><br />
Two: <input type="text" id="f2"><br />
Three: <input type="text" id="f3"><br />
Four: <input type="text" id="f4"><br />
<br />
<input type="button" id="mybutt" value="Go" />
javascript/jQuery:
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
}
}); //END mybutt.click
Note that the above example uses jQuery, so you must reference the jQ libraries (usually inside the head tags, something like this:)
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
EDIT:
Here is what the full HTML would look like:
<?php
//Any initial PHP code goes here
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//javascript
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$(document).ready(function() {
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
return false;
}
//If it gets to here, it passed validation
$('#yourForm').submit();
}); //END mybutt.click()
}); //END $(document).ready()
</script>
</head>
<body>
<form id="yourForm">
One: <input type="text" id="f1" /><br />
Two: <input type="text" id="f2" /><br />
Three: <input type="text" id="f3" /><br />
Four: <input type="text" id="f4" /><br />
</form>
<input type="button" id="mybutt" value="Click Me">
</body>
</html>
Note that, using the above scenario, no further PHP code would execute until the form is submitted, using the manual $('#yourForm').submit(); statement.

how to show an error message beside field in html using javascript please help me [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i wrote a program using javascript for showing error message beside field instead of alerting but it is not working please help me to work the program
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript">
function check()
{
if(document.getElementById('firstname').value==NULL || myform.firstname.value.length==0)
{
document.getElementById('errorname').value="this is an invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
<p>name</p>
<input type="text" name="firstname" onblur="check()"/>
<span id="errorname"></span>
<br/><input type="button" value="submit" />
</form>
</body>
</html>
you have not given the id to you textbox also pass the value of textbox into the function
like this
<input type="text" name="firstname" id="firstname" onblur="check(this.value)"/>
And JS Function
function check(value)
{
if(value.trim()=="")
{
document.getElementById('errorname').innerHTML="this is an invalid name";
}
}
SEE FIDDLE DEMO
You are not provided ID for your input field. Add an ID and access your input field.
function check(){
if(document.getElementById('firstname').value==""){
document.getElementById('errorname').innerHTML ="this is an invalid name";
}
}
And change your html field like this.
<input type="text" name="firstname" id="firstname" onblur="check()"/>
HTML:
<form id="form">
<p>name</p>
<input type="text" id="firstname" name="firstname" /> <span id="errorname"></span>
<br/>
<input type="submit" value="Submit" />
</form>
JavaScript:
var form = document.getElementById('form'),
firstName = document.getElementById('firstname'),
errorMessage = document.getElementById('errorname');
function check(event) {
event.preventDefault();
if (firstName.value === '' || !firstName.value.length) {
console.log('here')
errorMessage.innerText = 'This is an invalid name';
} else {
errorMessage.innerText = '';
}
}
form.addEventListener('submit', check);
JSFiddle example:
http://jsfiddle.net/2etd93jL/2/
You have used document.getElementById('firstname') but your input input type="text" name="firstname" doesn't have an id, only a name. try adding id="firstname" to the input box.
Multiple errors in your code listing down below:
Use of NULL: it is null and not NULL.
No id assigned as firstname and checking for that in the if loop
to give value to span need to use innerHTML
So your HTML code:
<form name="myform">
<p>name</p><input id="firstname" type="text" name="firstname" onblur="check()"/><span id="errorname"> </span>
<br/><input type="button" value="submit" />
</form>
JS Code:
function check()
{
if(document.getElementById('firstname').value==null || myform.firstname.value.length==0)
{
document.getElementById('errorname').innerHTML="this is an invalid name";
}
}
Working Fiddle
This is almost your code, few changes did to meet the requirement.
Checkout the fiddle
function check(){
if(document.getElementById('firstname').value=='' || !document.getElementById('firstname').value.length){
document.getElementById('errorname').innerHTML="this is an invalid name";
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<script type="text/javascript">
function check() {
if (document.myform.firstname.value === null || myform.firstname.value.length == 0) {
document.getElementById('errorname').innerHTML = "this is an invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
<p>name</p>
<input type="text" name="firstname" onblur="check()" /><span id="errorname"> </span>
<br />
<input type="button" value="submit" />
</form>
</body>
</html>

Categories