Not able to submit the form using jquery - javascript

Hi i have login form page where i validated using jquery. jquery script is checking for null values but when i entered the values it is not submittingbut i am able to see the alerts in else block
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
//$(this).hide();
var name = $.trim($("#uname").val());
var pwd = $.trim($("#pwd").val());
alert("Value: " + name);
alert("Text: " + pwd);
if(name == ''){
alert('ssss');
$(":input").css({
"background-color":"#FFCECE",
"border":"1px solid red"
});
// return false;
$('form').submit(function(){
//e.preventDefault();
return false;
});
}else{
alert('else');
$(":input").css({
"background-color":"",
"border":""
});
alert('else2');
$('form').submit(function(){
alert("thanks");
return true;
});
alert('else3');
}
});
});
</script>
This is my Html code
<form action="" method="post" name="loginform">
<table>
<tr>
<th>LOGIN PAGE</th>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="uname" id="uname" /></td>
<tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd" id="pwd" /></td>
<tr>
<tr>
<td colspan="2"><input type="submit" name="submit" id="submit" value="SUBMIT" /> </td>
<tr>
</table>
</form>
Thanks in advance..

Instead of
$('form').submit(function(){
alert("thanks");
return true;
});
in your else, just return true;
same in your if, you don't need to
$('form').submit(function(){
//e.preventDefault();
return false;
});
just return true;
What you're doing in your code is hooking up to the submit event of the form. If you return false or true from submit button, it'll submit the form or not.

Related

Don't send form data when to type no in confirm window

Type apple in the input whose name is goods,and type 9 in the input whose name is price,and click submit,now confirm window pop up,whatever your click yes or no,the data will send to price.php.
My expectation:
when you click yes ,the data will send to price.php,
when you click no ,the data will not send to price.php,what's wrong for my js?
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("click",check,false);
<form action="price.php" method="post">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
The price.php is simple.
<?php
var_dump($_POST);
?>
The exit below can't prevent form data from sending to price.php.
if(flag){
return true;
}else{
exit;
}
It is no use either to change exit; into return false;.
It is no use either to change js into below.
ob = document.getElementById("submit");
function check(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
exit;
}
}
}
ob.addEventListener("submit",check,false);
The traditional way is same as The KNVB did,the key point is <form action="price.php" method="post" onsubmit="return check()"> ,to bind form's attribute onsubmit with function check.
DOM0 level event way,almost the same like the traditional way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
ob.onclick =function(){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
What OP expect is the DOM2 level event way.
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('submit');
function check(event){
console.log(ob.type);
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("click",check);
</script>
</body>
</html>
The key points in DOM2 level event way are:
1.when flag is true
if(flag){
ob.submit();
return true;
}
2.when flag is false
else{
event.preventDefault();
return false;
}
This is my solution:
<html>
<body>
<form action="price.php" method="post" onsubmit="return check()">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
function check()
{
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
return true;
}else{
return false;
}
}
}
</script>
</body>
</html>
I tested it on Edge, IE11, Firefox, chrome browser, it works.
I found another solution:
<html>
<body>
<form action="price.php" method="post" id="form">
<table>
<tr>
<td>goods</td>
<td><input type="text" name="goods"></td>
</tr>
<tr>
<td>price</td>
<td><input type="text" id="price" name="price"></td>
</tr>
<tr><td colspan=2><input type="submit" id="submit" value="submit"></td></tr>
</table>
</form>
<script>
var ob = document.getElementById('form');
function check(event){
if(document.getElementById("price").value < 10){
var flag = window.confirm(" are your sure the price is less than 10 ?");
if(flag){
ob.submit();
return true;
}else{
event.preventDefault();
return false;
}
}
}
ob.addEventListener("submit",check);
</script>
</body>
</html>
A couple of things about the code:
exit - I've never seen before - is it javascript?
document.getElementById('price').value - returns a string - you should parse it (to a number) before comparing.
Use onsubmit="" attribute of the form - return true to allow form submission, false to block submission.
window.confirm already returns a boolean, just return that (instead of if statement).
Here's a bare-bones example:
function validate() {
const price = parseFloat(document.getElementById('price').value)
if (price < 10) {
return window.confirm("Are your sure the price is less than 10 ?")
}
return true // <- otherwise allow form submission
}
<form action="price.php" method="post" onsubmit="return validate()">
<input type="text" id="price" name="price">
<input type="submit" id="submit" value="submit">
</form>
Also, in general, try to condense your problem to the minimum code required to reproduce an issue.

How to clear a td content upon deleting/backspacing/clearing text in a textbox

I am working in php/JQuery and this is what I have coded so far ...
username.php
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
if($('#username').val().length == 0){
$('#message').empty();
}
else{
$("#message").html("<img src='images/loader.gif' /> checking...");
var username = $("#username").val();
$.post( "check.php", { user: $("#username").val() }, function (data){
if(data == 0){
$("#message").html("<img src='images/tick.png' /><span style='font-size:13px; color: black'> Username available</span>");
proceed = true;
}
else{
$("#message").html("<img src='images/err.png' /><span style=font-size:13px; color: red'> Username already taken</span>");
proceed = false;
}
});
}
});
});
</script>
</head>
<body>
<form id="user">
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="username" id="username"/></td>
<td id="message"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="text" name="password" id="password" /></td>
</tr>
</table>
<button type="submit" name="submit" >Check</button>
</form>
</body>
</html>
Now what I want to achieve is:
As I backspace/delete the whole text in the textbox with the ID = "username" , this should clear the text that appears in the td with the ID = "message"
How can achieve this with javascript.
Any help will be much appreciated.
Use keyup/input event instead of change or Both events together for backward compatibility.
Try this:
$(document).ready(function() {
$("#username").on('input, keyup', function() {
if ($('#username').val().length == 0) {
$('#message').empty();
} else {
$("#message").html("<img src='images/loader.gif' /> checking...");
var username = $("#username").val();
$.post("check.php", {
user: $("#username").val()
}, function(data) {
if (data == 0) {
$("#message").html("<img src='images/tick.png' /><span style='font-size:13px; color: black'> Username available</span>");
proceed = true;
} else {
$("#message").html("<img src='images/err.png' /><span style=font-size:13px; color: red'> Username already taken</span>");
proceed = false;
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="user">
<table>
<tr>
<td>Username</td>
<td>:</td>
<td>
<input type="text" name="username" id="username" />
</td>
<td id="message"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td>
<input type="text" name="password" id="password" />
</td>
</tr>
</table>
<button type="submit" name="submit">Check</button>
</form>

form validation javascript (error message showed and disappeared quickly)

i want to show the error messages next to the input element and if there's no error messages then send the data to the server (clear data from form) so fire the function on submit
http://codepen.io/anon/pen/RPNpNw
the problem is the error messages showed and disappeared quickly (blink)
but when change the input type to button
http://codepen.io/anon/pen/EjaZqe
will work but the data will be still in form and not cleared as input type="submit" will do
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<form>
<table style="width:50%;">
<tr>
<td>first name</td>
<td><input type="text" id="txtfname" /></td>
<td><span id="error"></span></td>
</tr>
<tr>
<td>age</td>
<td><input type="number" id="txtage" onblur="checkAge(txtage)" /></td>
<td><span id="errorage"></span></td>
</tr>
<tr>
<td>user name</td>
<td><input type="text" id="txtuser" /></td>
<td><span id="erroruser"></span></td>
</tr>
<tr>
<td>country</td>
<td>
<select onselect="checkSelect(this)" id="slct">
<option selected="selected" value="default">select your country</option>
<option>egypt</option>
<option>usa</option>
</select>
</td>
<td><span id="errorslct"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
</table>
</form>
<script>
function allvalidate() {
validate();
checkAge(txtage);
checkuser(txtuser);
checkSelect(this);
}
function validate() {
var txtf = document.getElementById('txtfname');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
//return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
function checkSelect() {
var select=document.getElementById('slct')
if (select.value=='default') {
document.getElementById('errorslct').innerText = ('you must choose country');
document.getElementById('errorslct').style.color = 'red';
return false;
}
else {
document.getElementById('errorslct').innerText = '';
return true;
}
}
</script>
</body>
</html>
Change
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
To:
<td><input type="submit" value="register" onclick="return allvalidate()" /></td>
Otherwise the boolean value is discarded. You also need to change allvalidate to actually return false if one of the validations fail:
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(txtage)) validated = false;
if (!checkuser(txtuser)) validated = false;
if (!checkSelect(this)) validated = false;
return validated;
}
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
well, I'm not expert but what I think is that data is not sending, you need to call the function on onsubmit event, instead of calling it on onclick event. It would send the data as well.

OCR Web Validation using Javascript

I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+='You must enter your name';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name='ExamEntry' method='post' action='success.html'>
<table width='50%' border='0'>
<tr>
<td id='name'>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td id='subject'>Subject</td>
<td><input type='text' name='subject' /></td>
</tr>
<tr>
<td id='examnumber'>Examination Number</td>
<td><input type='text' name='examnumber'></td>
</tr>
<tr>
<td id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...

How to execute Jquery onclick="" function only after JS validation

I wonder if I can execute onlick function only after JS validation any ideas?
I have a form which has e-amil and phone mandatory filed and i would like to check them before form is submitted , even more if everything is ok another div onclick="$('#dialog-links-blocks').show()" should be display with a message Thank you! How can I make it to be shown only after validation !
<script type="text/javascript">// <![CDATA[
function validateForm()
{
var x=document.forms["myform"]["phone"].value;
var y=document.forms["myform"]["email"].value;
if (x==null || x=="")
{
alert("Укажите номер телефона!");
return false;
}
if (y==null || y=="")
{
alert("Укажите email!");
return false;
}
}
// ]]></script>
<iframe name="hiddenFrame" width="320" height="240"></iframe>
<form id="validation" action="http://listovki.md/send_form_email.php" method="POST" name="myform" enctype="multipart/form-data" onsubmit="return validateForm()" target="hiddenFrame">
<table><colgroup> <col width="122" /> <col width="260" /> </colgroup>
<tbody>
<tr>
<td><label>имя</label></td>
<td><input type="text" name="family" /></td>
</tr>
<tr>
<td><label>почта</label></td>
<td><input type="email" name="email" /></td>
</tr>
<tr>
<td><label>gsm</label></td>
<td><input class="gsm" type="tel" name="phone" /></td>
</tr>
<tr>
<td colspan="2"><input class="aplicaAcumBt" onclick="$('#dialog-links-blocks').show()" type="submit" name="submit" value="отправить" /></td>
</tr>
</tbody>
</table>
</form>
Why not show div only if validation is true? why show only on click
<script type="text/javascript">// <![CDATA[
function validateForm()
{
var x=document.forms["myform"]["phone"].value;
var y=document.forms["myform"]["email"].value;
if (x==null || x=="")
{
alert("Укажите номер телефона!");
return false;
}
if (y==null || y=="")
{
alert("Укажите email!");
return false;
}
// Validation is true here
$('#dialog-links-blocks').show()
}
</script>

Categories