Posting to a separate document using <form> and POST - javascript

My first post here #stackoverflow. Please bear with me.
Look at the code below. I want the javascript to post to an PHP (applybeta.php) document IF there is a '#' in the field with the name & id 'epost'. If there isn't a '#' in the field, a messagebox will pop up telling the user they entered an invalid e-mail address.
If you don't enter a '#' the message box shows up. But if you do enter a valid email it doesn't post to "applybeta.php", nothing happens at all. Anybody got an idea why? Sorry if the description is vague, hopefully you'll figure out what I mean :)
The e-post field got both an id and a name because I tried with both, none of them works.
<!DOCTYPE html>
<html>
<head>
<title>Binärklocka</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="index.css">
<link href='http://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>
<!-- table font --> <link href='http://fonts.googleapis.com/css?family=Lato:900italic' rel='stylesheet' type='text/css'>
</head>
<body>
<script>
function kollaepost() {
var x = document.getElementById("email");
if(x.value.indexOf('#') === -1) {
alert("You didn't enter a valid E-mail address!");
}
else {
document.getElementById("minForm");
//z.submit();
//alert("hej");
}
}
</script>
<div id="wrap">
<div id="main">
<br>
<br>
<table id="nav">
<tr>
<td>Store</td>
<td>Our Products</td>
<td><img src="home.png" alt="hem" width="60" height="60"/></td>
<td>About Us</td>
<td>Contact</td>
</tr>
</table>
<hr id="linje1" />
</div>
</div>
<p id="binaryclock" onclick="showLink()">
We are looking for beta testers for our newly created clock!<br />
To participate, fill in the forms below with your real name</br />
and a valid e-mail address and a download link will appear.
</p>
<!-- Form that I want to post -->
<div id="applybeta">
<form action="apply.php" method="post" id="minForm" name="minForm">
<input type="text" placeholder="Full name" name="name" /><br />
<!-- checking this field for '#' -->
<input type="text" placeholder="E-mail" id="email" /><br /><br />
<!-- end of field -->
<input onclick="kollaepost()" type="button" name="submit" value="Send" /><br />
</form>
</div>
<!-- End of the form -->
<div id="dlink">
shdgfghClick here to download
</div>
<div id="bottomtext">
<p># 2015 ClockMasters Elite</p>
</div>
</body>
</html>

Instead of having an input of type button, try submit. Your onclick-function can then serve as a validation function by returning true or false, and thus influence whether the form will be submitted. Something like this:
<input onclick="return kollaepost()" type="submit" name="submit" value="Send" />
and:
<script>
function kollaepost() {
var x = document.getElementById("email");
if(x.value.indexOf('#') === -1) {
alert("You didn't enter a valid E-mail address!");
return false;
}
return true;
}
</script>
Also see this question for a more detailed explanation on this method, in general.

You can submit your form using the .submit() method.
var fromElement = document.getElementById("minForm");
formElement.submit();
For further reference, see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

Related

Validation in javascript is not working as it should

I have been trying to solve the problem that I am having with this email validation in JavaScript, but all the code I have tried was having the same problem. When I used the developer tool in google chrome I didn't see any error message, so I don't understand why is this happening. I want to show the error message if an email is not valid.
What am I missing?
link full code - https://jsfiddle.net/lmanhaes/cq1g5dyt/14/
Thanks.
function checkEmail(validate) {
let re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let email = validate.userName.value;
if (email === re)
return true;
else {
error.setAttribute("class", "error");
error.innerHTML = ("Email is not correct. Please retype.");
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<section>
<h1></h1>
<ul>
</ul>
<h1>Register</h1>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="registerDetails" action="lmanha01_fma_t3confirm.html">
<div>
<label for="username">* Userame:</label>
<input type="text" id="userName" required>
<!--pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$"-->
<!--check that the user has in fact typed in an email address-->
<div id="error"></div>
</div>
<div>
<label for="password">* Password (must be 8 characters exactly and include one Uppercase, one
lowercase and
one number):</label>
<input type="password" id="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,8}$"
required>
<input type="checkbox" id="showpasswords" onclick="Toggle()">
<!--This creates a toggle effect-->
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
<!--moved to the bottom to load the page faster-->
<script src="scripts/exemple.js"></script>
</body>
</html>
You should use test() method of regex to return true or false if input value matches the email pattern.
if (re.test(email)){
//logic when it is valid
}
else{
//logic when it is invalid
}
const email = document.getElementById('email');
function validate(){
const regex=/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return regex.test(email.value) ?console.log("Valid"):console.log("Invalid");
}
<input type="email" id="email" />
<button onclick="validate()">
Validate
</button>

Multiple input boxes - alertifyjs / Jquery

I am trying to create a prompt dialog box using alertifyjs that has multiple input boxes. I have managed to create the dialog box to show the multiple boxes but I cant seem to make a reference to the inputs that user provides.
I want to write if statement that carries out action based on user input when they press OK. However, the OK button doesnt seem to be working and also the if-statements don't work as well. I am not sure what I might be doing wrong, can someone please help me.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/alertify.min.css"/>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/themes/bootstrap.min.css"/>
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/alertify.min.js"></script>
</head>
<body>
<div style="display:none;" >
<div id="dlgContent">
<p> Enter Value One </p>
<input class="ajs-input" id="inpOne" type="text" value="Input One Default Value"/>
<p> Enter Value Two </p>
<input class="ajs-input" id="inpTwo" type="text" value="Input two default Value"/>
</div>
</div>
<!-- the script -->
<script>
var dlgContentHTML = $('#dlgContent').html();
$('#dlgContent').html("");
alertify.confirm(dlgContentHTML).set('onok', function(closeevent, value) {
var inpOneVal = $('#inpOne').val();
var inpTwoVal = $('#inpTwo').val();
updateListItems(inpOneVal,inpTwoVal);
if (inpOneVal == "test" && inpTwoVal == "test") {
alertify.success('Successful');
} else {
alertify.error('Wrong')
}
}).set('title',"Update");
</script>
</body>
</html>
Link to JSfiddle: http://jsfiddle.net/1qouxdkc/4/
In your script you call a function named updateListItems(inpOneVal,inpTwoVal);
As that function is not declared anywhere, it errors, so with that temporarily commented out, it works.
Stack snippet
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/alertify.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/css/themes/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/alertifyjs#1.11.1/build/alertify.min.js"></script>
</head>
<body>
<div style="display:none;">
<div id="dlgContent">
<p> Enter Value One </p>
<input class="ajs-input" id="inpOne" type="text" value="Input One Default Value" />
<p> Enter Value Two </p>
<input class="ajs-input" id="inpTwo" type="text" value="Input two default Value" />
</div>
</div>
<!-- the script -->
<script>
var dlgContentHTML = $('#dlgContent').html();
$('#dlgContent').html("");
alertify.confirm(dlgContentHTML).set('onok', function(closeevent, value) {
var inpOneVal = $('#inpOne').val();
var inpTwoVal = $('#inpTwo').val();
//updateListItems(inpOneVal,inpTwoVal);
if (inpOneVal == "test" && inpTwoVal == "test") {
alertify.success('Successful');
} else {
alertify.error('Wrong')
}
}).set('title', "Update");
</script>
</body>
</html>

Tag <p> doesn't keep the value received from a <script>

i'm testing a HTML using a to check what a servlet returned,
to choose which message i'll show. The app runs ok, the servlet returns correctly. The get what the servlet returned and chooses the message. But, the tag shows the message only for a second (like a flash) and erase shortly thereafter. Below you can see my code:
<!DOCTYPE html>
<html lang ="pt-br">
<head>
<title> loginServlet2 </title>
<meta http-equiv = ”Content-Type” content=”text/html; charset=UTF-8”>
<link rel="stylesheet" type="text/css" href="c:/java/html/css/estilo.css"/>
<script>
function oMsg()
{
var wMsg1 = document.getElementById('wMsg').innerHTML;
if (wMsg1 == "Test OK!")
{
document.getElementById('wMsga').innerHTML="Test is OK";
}
else
{
document.getElementById('wMsga').innerHTML="Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="text" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<p id="wMsg"> Msg1 : <%=request.getAttribute("wMsg")%></p>
<p id="wMsga"> Msg2 : </p>
</body>
</html>
Could you help me, please? Thanks.
I'm not sure if I'm answering what you are looking for, but adding return false to onclick will keep you on the same page:
<input type="submit" value="Submit" name="B1" onclick="oMsg(); return false;">

Php search form shows results without pressing the search button when it should wait until the button is pressed to show them

As the title suggests I'm trying to show the results of a query and it works properly, but it shows the results automatically beneath the search button, when it should wait for the button to be pressed and then reload the page and show the results. I'm kind of sure that it's a problem with the code but I cannot find where. I know it's a stupid question but all help is appreciated.
Here is my code:
<?php
mysql_connect('localhost', 'root', 'Passw0rd') or die(mysql_error());
mysql_select_db("cvtool") or die(mysql_error());
include("include/session.php");
$username = $_SESSION['username'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!--The viewport tag is used in order to scale the page properly inside any screen size -->
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>CV Tool</title>
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="css/main.css"/>
<!--Import JQuery from stored file -->
<script src="js/jquery-1.11.1.min.js"></script>
<!--Import JQuery from Google's Content Delivery Network -->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">-->
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="js/menu.js"></script>
<script type="text/javascript" src="js/backToTop.js"></script>
</head>
<body>
<!--Big wrapper contains the whole site (header,navigation menu,....,footer-->
<div id="big_wrapper">
<header id="top_header">
<img src="images/cvlogo.png">
</header>
<br>
<nav class="clearfix">
<ul class="clearfix">
<li>Home</li>
<?php
/**
* User has already logged in, so display relavent links, including
* a link to the admin center if the user is an administrator.
*/
if($session->logged_in){
echo "<li>Search</li>"
."<li>My CV(s)</li>"
."<li>My Account</li>"
;
echo "<li>Logout</li>";
}
else
?>
</ul>
Menu
</nav>
<section id="main_section">
<?php
/**
* User not logged in, display the login form.
* If user has already tried to login, but errors were
* found, display the total number of errors.
* If errors occurred, they will be displayed.
*/
if($form->num_errors > 0){
echo "<font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font>";
}
?>
<form action="search.php" method="GET" >
<h1>Search for an CV</h1>
<h3>Department</h3>
<br/>
<select id="dropDown">
<option value="">Choose a department</option>
<option value="Comp">Computer Science</option>
<option value="Bus">Business Studies</option>
<option value="Psy" >Psychology</option>
<option value="Eng">English Studies</option>
</select>
<br/>
<h3>Skills</h3>
<br/>
<div id="Comp"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Java
<input type="checkbox" name="whatever" />
AI
<input type="checkbox" name="whatever" />
Web Development
</div>
<div id="Bus"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Business 1
<input type="checkbox" name="whatever" />
Business 2
<input type="checkbox" name="whatever" />
Business 3
</div>
<div id="Psy"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Psychology 1
<input type="checkbox" name="whatever" />
Psychology 2
<input type="checkbox" name="whatever" />
Psychology 3
</div>
<div id="Eng"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
English Studies 1
<input type="checkbox" name="whatever" />
English Studies 2
<input type="checkbox" name="whatever" />
English Studies 3
</div>
<script>
$(document).ready();
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
});
</script>
</form>
<form action="search_result.php">
<input type="submit" name="search" id="search" value="Search" />
<div id="search"></div>
<script>
$(document).ready(function(){
$("#dropDown").change(function(){
var data = $(this).val();
$.ajax({
type:'POST',
data:'search_value='+data,
url:'search_result.php',
success:function(data){
$("#search").html(data);
}
});
});
});
</script>
</form>
</section>
<footer id="the_footer">
City CV Tool 2014
</footer>
</div>
</body>
</html>
it's because of this line
$("#dropDown").change(function(){
add a submit button in the form if that's what you want then run the function off that
<input type="submit" value="Submit" />
Edited after rwacarter's correct comments below about accessability
Add an Id to the form tag
<form id="searchformSubmit"
then do
$("#searchformSubmit").on('submit',function(){
this should also work if the user presses the enter key to submit rather then the button provided you have only the one form on the page
The reason why the page is reloading is because any <button> or or <input type='submit'> inside a HTML form will reload the page, unless you have onClick='return false;' on them. I think you need to add:
onClick="startsearch();return false;"
on the submit button. You'll also have to send the form data with it. To do this, make a variable with this:
var form_data = $('#form').serialize();
and send it with:
$.post('search_result.php', {form: form_data}, function(data) {$("#search").html(data);})
Your ajax call (result search) is called when your dropdown change (click, user input, ...), but you should bind the action to your form click
$(document).ready(function(){
$("#search").click(function(){
var data = $("#dropDown").val();
$.ajax({
type:'POST',
data:'search_value='+data,
url:'search_result.php',
success:function(data){
$("#search").html(data);
}
});
});
});
In addition, this is not necessary to specify the action in your form however it will trigger the form action and redirect you to the page search_result.php, I suggest you to update it and set action="#"

Why is the a form fade function not allowing validation?

Is this code correct? I want the 'submit' to validate the field (to make sure a value has been entered) and if this is correct (there is a value) then fade and display.
Currently, the form fades even when no value is entered? I feel I'm missing something really simple here!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />
<link rel='stylesheet' type='text/css' href='styles.css' />
<meta charset="utf-8"-->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<div id="sidebarf">
<form id="sidebarform" name="myForm" onsubmit="return validateForm()" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" required>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
<script>
$("#sidebarformsubmit").click( function(){
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() )
});
});
</script>
</body>
</html>
Judging by your comment on the other answer, you don't care if this actually gets submitted, so you could do the following:
HTML:
<div id="sidebarf">
<form id="sidebarform" name="myForm" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" />
<input type="submit" id="sidebarformsubmit" value="Submit" />
</form>
JS:
$(document).ready(function() {
$('#sidebarform').on('submit', function() {
if ($('#sidebarusername').val() == '') {
alert('First name must be filled out');
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() );
});
return false;
});
});
Working example:
http://jsfiddle.net/3z5x8/
Your validation is bound to the submit event. The click event will always be fullfilled.
Bind your handler to the submit event also
$("#sidebarformsubmit").submit( function(){.....
Unless you are submitting with ajax the form will cause a page refresh also which means your fade and show new html won't work

Categories

Resources