This question already has answers here:
How to stop form submit during ajax call
(7 answers)
Closed 8 years ago.
I'm working on a website and I have this change_password.php script which is a 3 fields where the user puts his last password, his new password and his new password for a second time. I've tried to make a verification if the second and the third matches. If they don't I show an alert to the user.
The problem is that it does show the alert when the password are different but it redirects to the next page, do_change_password.php anyway. What can I do to fix it?
<html>
<?php
session_start(); // começa a session
require "config.php";
if(Check_Login_Status())
{
Update_Login_Status();
}
else
{
session_unset();
phpAlert_Redirect("ACESSO NEGADO", "index.php");
exit();
}
?>
<head>
<meta charset = 'UTF-8'>
<link rel="shortcut icon" href="images/favicon.ico"/>
<title>Sistema de Estágios - UFMS - Login</title>
<link href = "css/bootstrap.css" rel = "stylesheet" >
<link href = "css/index.css" rel = "stylesheet" >
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("input").blur(function()
{
if($(this).val() == "")
{
$(this).css({"border" : "1px solid #F00"});
}
else
$(this).css({"border" : "1px solid #FFF"});
});
$("#botao").click(function()
{
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
cont++;
});
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x == y)
$("#form").submit();
else
alert("Senhas não conferem");
}
});
});
</script>
</head>
<body>
<?php
Set_Barra_Superior($_SESSION["auto"]);
?>
<center>
<div class = "container">
<div class = "principal">
<form id="form" name="Form" method="post" action="do_change_password.php">
<p>
<label for="a">Senha antiga:</label>
<input id="a" name="old_pass" type="password" class="form-control"/><br/>
</p>
<p>
<label for="b">Nova Senha:</label>
<input id="b" name="new_pass" type="password" class="form-control"/><br/>
</p>
<p>
<label for="c">Confere nova senha:</label>
<input id="c" name="conf_pass" type="password" class="form-control"/><br/>
</p>
<button id="botao" name="botao" value="login" class="btn btn-primary" style="width: 100%;">Login</button>
</form>
</div>
</div>
</center>
</body>
Add the event into the click function, call preventDefault on the event and then return false.
$("#botao").click(function(e)
{
e.preventDefault();
var cont = 0;
$("#form input").each(function()
{
if($(this).val() == "")
cont++;
});
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x == y)
$("#form").submit();
else
alert("Senhas não conferem");
}
return false;
});
Try returning false like:
if(cont == 0)
{
var x = document.forms["Form"]["new_pass"].value;
var y = document.forms["Form"]["conf_pass"].value;
if(x != y)
{
alert("Senhas não conferem");
return false;
}
}
Related
I am currently working on a web application project.
I have completed the design of the registration page.
I have used jQuery for input validation, and so far everything is working as expected.
However, when I click on the Register (submit) button, the form does not submit.
I am using php, MySQL, JavaScript, CSS, and Bootstrap for the task.
Below is my code in register.php file:
**<?php
// Include config file
require_once "./config/connection.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"])))
{
$username_err = "Please enter your email";
}
else
{
// Prepare a select statement
$sql = "SELECT email FROM users WHERE username = ?";
if($stmt = mysqli_prepare($con, $sql))
{
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt))
{
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1)
{
$username = trim($_POST["username"]);
}
else
{
$username_err = "The email provided does not belong to your organization";
}
}
else
{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($con);
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>DEMO TELEPHONE DIRECTORY</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./bootsstrap/bootstrap-3.3.5-dist/css/bootstrap.min.css">
<!-- <script src="/"jquery-ui-1.11.4/jquery-ui.min.js" ></script> -->
<link rel="stylesheet" href="./css/index.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="./bootsstrap/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
<script src="./js/register.js" type="text/javascript"></script>
</head>
<body>
<div class="container-fluid">
<div id="loginpanel">
<form name="loginform" id="registrationform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<h1>Register</h1>
<div class="form-group">
<label for="usernameregistration">Email</label>
<input class="form-control" id="usernameregistration" type="text" placeholder="Email" name="username" required autofocus/>
<p id="usernameerror" class="alert-error <?php echo (empty($username_err)) ? 'hideerror' : '';?>" role="alert"><?php echo $username_err; ?></p>
</div>
<div class="form-group">
<label for="passwordregistration">Password</label>
<input class="form-control" id="passwordregistration" type="password" placeholder="Password" name="password" required/>
<p id="registrationpassworderror" class="alert-error hideerror" role="alert" ></p>
</div>
<div class="form-group">
<div class="form-group">
<label for="confirmpasswordregistration">Confirm Password</label>
<input class="form-control" id="confirmpasswordregistration" type="password" placeholder="Confirm Password" name="confirmpassword" required/>
<p id="confirmregistrationpassworderror" class="alert-error hideerror" role="alert"></p>
</div>
<div class="form-group">
<button class="btn btn-primary btn-md btn-block" name="btnregister" id="btnregister" type="submit">Register</button>
</div>
<div class="form-group">
<span>Already registered? </span><span>Click here to login</span>
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
</body>
</html>**
Below is my JavaScript code in register.js file:
**$(document).ready(function(){
// Validate Username
$('#usernameerror').html('').addClass('hideerror');
let usernameerror = true;
$('#usernameregistration').keyup(function () {
validateUsername();
});
function validateUsername() {
let username = $('#usernameregistration').val();
if (username.length == '') {
$('#usernameerror').html('Please enter your email').removeClass('hideerror');
usernameerror = false;
return false;
}
else {
$('#usernameerror').html('').addClass('hideerror');
}
}
// Validate Email
$('#usernameerror').html('').addClass('hideerror');
let emailerror = true;
$('#usernameregistration').keyup(function () {
validateEmail();
});
function validateEmail() {
let email = $('#usernameregistration').val();
if (email.length != '')
{
if (isEmail(email))
{
$('#usernameerror').html('').addClass('hideerror');
}
else
{
$('#usernameerror').html('The email is invalid').removeClass('hideerror');
emailerror = false;
return false;
}
}
}
function isEmail(email) {
let regexEmail = /^([_\-\.0-9a-zA-Z]+)#([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
return regexEmail.test(email);
}
// Validate Password
$('#registrationpassworderror').html('').addClass('hideerror');
let passworderror = true;
$('#passwordregistration').keyup(function () {
validatePassword();
});
function validatePassword() {
let password = $('#passwordregistration').val();
if (password.length == '') {
$('#registrationpassworderror').html('Please enter your password').removeClass('hideerror');
passworderror = false;
return false;
}
else if (password.length < 6) {
$('#registrationpassworderror').html('Password length should be at least 6 characters').removeClass('hideerror');
passworderror = false;
return false;
}
else {
$('#registrationpassworderror').html('').addClass('hideerror');
}
}
// Validate Confirm Password
$('#confirmregistrationpassworderror').html('').addClass('hideerror');
let confirmpassworderror = true;
$('#confirmpasswordregistration').keyup(function () {
validateConfirmPassword();
});
function validateConfirmPassword() {
let password = $('#passwordregistration').val();
let confirmpassword = $('#confirmpasswordregistration').val();
if (confirmpassword.length == '') {
$('#confirmregistrationpassworderror').html('Please confirm your password').removeClass('hideerror');
confirmpassworderror = false;
return false;
}
else if (confirmpassword != password) {
$('#confirmregistrationpassworderror').html('Password and Confirm Password do not match').removeClass('hideerror');
confirmpassworderror = false;
return false;
}
else {
$('#confirmregistrationpassworderror').html('').addClass('hideerror');
}
}
// Submit button
$('#btnregister').click(function () {
validateUsername();
validatePassword();
validateConfirmPassword();
validateEmail();
if ((usernameerror == true) &&
(passworderror == true) &&
(confirmpassworderror == true) &&
(emailerror == true)) {
return true;
} else {
return false;
}
});
});**
Finally, below is my css code in index.css file:
**#loginpanel
{
margin:0 auto;
width: 300px;
position: relative;
top:150px;
background-color: beige;
padding:20px;
border-radius: 0px;
}
#errormsg
{
clear:both;
position: relative;
top:250px;
}
.hideerror
{
display: none;
}
.alert-error
{
color: red;
margin-bottom: -15px;
}**
I am suspecting the my jQuery code to be the culprit but can't seem to figure out how to allow submit after successful input validation. Kindly help.
That's a lot of jquery code going on. I would advise to start with the basics, how do we prevent a form from submitting when user clicks the button:
<form onsubmit="validate(event)">
<input name="var1" value="xxx">
<button>Submit</button>
</form>
<script>
function validate(event) {
var formIsValid = true;
if (formIsValid) {
// let the browser submit the form.
} else {
// prevent the form submitting.
event.preventDefault();
}
}
</script>
Whenever a submit button is clicked / the user attempts to submit the form we can listen to the 'submit' event.
If we call preventDefault on the submit event we can stop the user from submitting an invalid form.
In your example you could change the $('#btnregister').click function to $('form').submit(function(event) { event.preventDefault(); })
Try to send form use jQuery method submit if validation is ok
if ((usernameerror == true) &&
(passworderror == true) &&
(confirmpassworderror == true) &&
(emailerror == true)) {
$('#registrationform').submit();
} else {
return false;
}
In the application I'm developing I have an admin panel in that panel there a function to create, edit and delete users.
In the form I create 3 user types using a while loop which drags data from a database and the 3 user types are:
Admin
Manager
User
HTML Form:
<?php
/**
* Created by PhpStorm.
* User: SiNUX
* Date: 4/6/2017
* Time: 3:41 PM
*/
session_start();
include_once("../iConnect/handShake.php");
$getUserRole = "SELECT * FROM userroles ORDER BY urId ASC";
$getUserRoleQuery = $dbConnect -> query($getUserRole);
?>
<html>
<head>
<title>Timer User Creation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Style Sheets -->
<link rel="stylesheet" type="text/css" href="../../CSS/main.css">
<!-- Java Scripts -->
<script language="JavaScript" type="text/javascript" src="../../jScripts/jquery-3.2.0.min.js"></script>
<script language="javascript" type="text/javascript" src="../../jScripts/svrTimeDate.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/reload.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/setMsg.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/userCreatFunctions.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/multiScript.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/getIds.js"></script>
</head>
<body onload="pauseLoad4()">
<div id="divCenter" class="box">
<label id="userName">Hello <?php echo $_SESSION["fName"]." ".$_SESSION["lName"]; ?></label><br><br>
<label id="uId" hidden>1</label>
<div style="width: 166px; position: absolute; left: 642px; top: 20px; height: 44px;">
<img src="../../images/logo.png" width="142" height="33">
</div>
<label for="date">Date:</label>
<label id="date" style="margin-left: 50px;"></label><br><br>
<label for="fName">First Name:</label>
<input type="text" id="fName" name="fName" style="margin-left: 10px;" onkeyup="checkEmpty();">
<label for="lName" style="margin-left: 8px;">Last Name:</label>
<input type="text" id="lName" name="lName" style="margin-left: 10px;" onkeyup="checkEmpty();" disabled>
<label for="uName" style="margin-left: 8px;">User Name:</label>
<input type="text" id="uName" name="uName" style="margin-left: 7px;" onkeyup="checkEmpty();" disabled><br><br>
<label for="pWord1" style="margin-left: 8px;" >Password:</label>
<input type="password" id="pWord1" name="pWord1" style="margin-left: 17px;" onkeyup="checkLength();" disabled>
<label for="pWord2" style="margin-left: 8px;">Confirm Password:</label>
<input type="password" id="pWord2" name="pWord2" style="margin-left: 8px;" onkeyup="checkPass();" disabled>
<label for="uTeam" style="margin-left: 8px;">Team</label>
<select name="uTeam" id="uTeam" style="width: 170px;" onchange="teamId(this.id);enableRoles();" disabled>
<option></option>
</select>
<input type="text" name="uTeamId" id="uTeamId" hidden><br><br>
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
<label id="msgID" hidden></label>
<div id="msg"></div>
<div id="sbmBtns">
<input type="button" value="Reset" name="reset" id="reset" class="btn" onclick="resetForm()">
<input type="button" value="Submit" name="submit" id="submit" class="btn" onclick="pauseLoad3();" disabled>
</div>
</div>
</body>
</html>
I use a JavaScript to validate the form and to enable the next text box if the validation criteria is met.
JavaScript:
function checkEmpty() {
var msg = document.getElementById('msg'),
fName = document.getElementById('fName'),
lName = document.getElementById('lName'),
uName = document.getElementById('uName'),
pass1 = document.getElementById("pWord1");
//Using ajax made the function to check if the text box value is empty or not
//when that text box has focus.
if ($("#fName").is(':focus')){
if (fName.value.length <= 3){
msg.innerHTML = "First name is too short";
}else{
msg.innerHTML = "";
lName.disabled = false;
}
}
if ($("#lName").is(':focus')){
if (lName.value === fName.value){
msg.innerHTML = "Last and first name can't be the same";
pass1.disabled = true;
}else{
if (lName.value.length <= 3){
msg.innerHTML = "Last name is too short";
}else{
msg.innerHTML = "";
uName.disabled = false;
}
}
}
if ($("#uName").is(':focus')){
if (uName.value.length <= 3){
msg.innerHTML = "User name is too short";
pass1.disabled = true;
}else{
if(uName.value.length > 0){
checkUname();
}
}
}
function checkUname() {
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
if (xmlhttp.responseText === "1"){
msg.innerHTML="Username taken";
pass1.disabled = true;
}else{
msg.innerHTML = "";
pass1.disabled = false;
}
}
};
xmlhttp.open("POST","../Functions/matchUname.php?uName="+uName.value,true);
xmlhttp.send();
}
}
function checkLength() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
passLength1 = pass1.value.length;
if(passLength1 <= 4){
document.getElementById("msg").innerHTML ="Password is less than 4 characters!";
}else{
document.getElementById("msg").innerHTML ="";
pass2.disabled = false;
}
}
function checkPass() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
uTeam = document.getElementById("uTeam"),
matchColor = "#66cc66",
noMatchColor = "#ff6666";
if (pass1.value === pass2.value){
document.getElementById("msg").innerHTML ="Passwords match!";
pass1.style.backgroundColor = matchColor;
pass2.style.backgroundColor = matchColor;
uTeam.disabled = false;
}else{
document.getElementById("msg").innerHTML ="Passwords do not match!";
pass1.style.backgroundColor = noMatchColor;
pass2.style.backgroundColor = noMatchColor;
}
}
function enableRoles() {
var team = document.getElementById("uTeam").value,
teamId = document.getElementById("uTeamId").value,
tlCheck = document.getElementById("tl"),
role = document.getElementsByClassName("userRoles");
if (team !== ""){
//For loop to enable radio buttons
for (var i = 1; i < role.length; i++){
role[i].disabled = false;
//This part will take the team is from uTeamId text box
//send it to getTeam.php checks if that team has a leader if that team has a leader
//"set" value will be returned making the check box for team attribute team leader disabled.
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
// document.getElementById("msgID").innerHTML = xmlhttp.responseText;
tlCheck.disabled = xmlhttp.responseText === "set";
}
};
xmlhttp.open("POST","../Functions/getTeam.php?teamId="+teamId,true);
xmlhttp.send();
}
}
}
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
It's working with out any errors but I want to disable the Admin user type if the logged in user is not a admin. I can get this done by using pure PHP but it breaks the flow of the form.
In my HTML/PHP form I have used PHP to archive what I'm describing but it not really what want to do I want use JavaScript or jQuery or AJAX to archive this.
The PHP I use:
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
Can some direct me down the right path or show me how to do this.
UPDATE:
After talking with professionals I learned that what I was trying to do is to shoot my self in the foot by my own gun. It's a bad idea to use client side languages to handle security options and WE CAN'T TRUST THE USER. My main issues was the flow of the form but security trumps the beauty so this will be split in to another one which the normal user want even see the admin option.
I would like to leave this question here and don't mind if it get closed so others can learn something from my mistake.
Just to nail this one down...
After a nice chat discussion, it appears that Jack (OP) has understood the importance not to manage user level security on client side.
The questions no longer needs more answer.
;)
I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>
Here is my code :
when after i entered name and email the form validation isn't performing.What should i do to validate the user entered data.And i would to like to move to another jsp page of name start.jsp when i click on Participate Kindly help me to get rid of this and please tell me what and why itsn't working..
<html>
<head>
<title>Aptitude Competition Online</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script language="javascript">
function isEmpty(str) {
if(str=="" )
{
return true;
} else return false;
}
function validate() {
var nam = document.form[0].name.value;
var ema = document.form[0].email.value;
if(isEmpty(nam))
{
alert(Name should be filled out");
document.form[0].name.focus;
return false;
}
else if(isEmpty(ema)
{
alert(E-mail should be filled out");
document.form[0].email.focus;
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<div id="header1">
<font id="font1">Aptitude Quiz</font>
</div>
<div id="email">
<div id="inside">
<font id="font2">Welcome to Aptitude Quiz</font><br><br><br>
<form name="form">
Name : <input type="text" name="name"><br><br>
E-mail : <input type="text" name="email"><br><br>
<input name="Participate" type="button" value="Participate" onClick="validate()"><br><br>
</form>
</div>
</div>
<div id="footer">
Contact Us : gmail#name.com
</div>
</body>
</html>
<script type="text/javascript">
function isEmpty(str)
{
if (str == "")
{
return true;
}
else
{
return false;
}
}
function validate()
{
var nam = document.form.name.value
var ema = document.form.email.value;
if (isEmpty(nam))
{
alert("Name should be filled out");
document.form.name.focus();
return false;
}
else if (isEmpty(ema))
{
alert("E-mail should be filled out");
document.form.email.focus();
return false;
}
else
{
return true;
}
}
</script>
Change only the script part
Change as per this
<form name="form" method = "post" onsubmit = "return validate();">
Name : <input type="text" name="name"><br><br>
E-mail : <input type="text" name="email"><br><br>
<button name="Participate" value="Submit" type = "submit"><br><br>
</form>
<html>
<head>
<title>Aptitude Competition Online</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script type="text/javascript">
function validate()
{
var nam = document.forms[0].name.value;
var ema = document.forms[0].email.value;
if(nam == "")
{
alert("Name should be filled out");
//document.forms[0].name.focus;
document.getElementById("name").focus();
return false;
}
else if(ema =="")
{
alert("E-mail should be filled out");
//document.forms[0].email.focus;
document.getElementById("email").focus();
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<div id="header1">
<font id="font1">Aptitude Quiz</font>
</div>
<div id="email">
<div id="inside">
<font id="font2">Welcome to Aptitude Quiz</font><br><br><br>
<form name="form">
Name : <input type="text" name="name" id="name"><br><br>
E-mail : <input type="text" name="email" id="email"><br><br>
<input name="Participate" type="button" value="Participate" onClick="validate()"><br><br>
</form>
</div>
</div>
<div id="footer">
Contact Us : gmail#name.com
</div>
</body>
</html>
I have this next code
<!doctype html>
<html class="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nieuwe gebruiker | Sociale buurt</title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="onzebuurt.css" rel="stylesheet" type="text/css">
<script type="text/javascript" language="javascript">
function formulierValideren() {
if (document.getElementById('Username').value == '' || document.getElementById('Username').value == null)
{
alert ('Gebruikersnaam is verplicht.');
document.getElementById('Username').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord').value == '' || document.getElementById('Wachtwoord').value == null)
{
alert ('Wachtwoord is verplicht.');
document.getElementById('Wachtwoord').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value == '' || document.getElementById('Wachtwoord2').value == null)
{
alert ('Bevestig wachtwoord.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value != document.getElementById('Wachtwoord').value)
{
alert ('Wachtwoorden komen niet overeen.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else
{
$("#bevestig").click(function() {
gebruikerToevoegen();
});
var msg = "Registratie succesvol. Klik op OK om u aan te melden op de site.";
if(confirm(msg)){
setTimeout(function() {window.location.href = "http://webs.hogent.be/kevinbaeyens/"})
}
}
//end if
}//end function
function gebruikerToevoegen() {
var request = new XMLHttpRequest();
request.open("POST", url);
request.onload = function() {
if (request.status == 201){
alert("everything OK!");
} else {
alert("you're wrong");
}
};
}
</script>
</head>
<body class="body2">
<div class="gridContainer clearfix">
<div class="header1">
<center>
Nieuwe gebruiker
</center>
</div>
<div id="formulier2">
<form method="post" name="form" action="">
<p class="labels"><center>Gebruikersnaam *</center></p><input id="Username" type="text" name="Username" placeholder="Gebruikersnaam" size="50">
<p class="labels"><center>Wachtwoord *</center></p><input id="Wachtwoord" type="password" name="Wachtwoord" placeholder="Wachtwoord" size="50">
<p class="labels"><center>Bevestig wachtwoord *</center></p><input id="Wachtwoord2" type="password" name="Bevestig wachtwoord" placeholder="Bevestig wachtwoord" size="50">
<br />
<center><img id="return" name="jsbutton" src="return.png" alt="Terug" /></center>
<br />
<center><input id="bevestig" type="image" src="Bevestig.png" width="200" height="50" border="0" alt="SUBMIT!" onclick="formulierValideren()"></center>
<br />
</form>
</div>
</div>
</body>
</html>
I want to send the data from #Username and #Wachtwoord to my MySQL database.
Please help me please, i'm stuck on this for almost a week now. i'll be so happy if anyone could help me! if i need to give more information, please ask me
first I thought you were looking for a client side solution (which woul be a very bad idea anyway). Jason is right. But if you want something kind of automatic, have a look to smarty php. Though, first you have to learn some basic stuff and a watch very clear example you could find in this video tuto: http://www.youtube.com/watch?v=gvGb5Z0yMFY
1) Why are you using a framework (seems jQuery) and dooing something like this
var request = new XMLHttpRequest();
You may have a look at: http://api.jquery.com/jQuery.ajax/
2) It would recommend, to use e.preventDefault instead of returning false on validation.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
3) What are you doing in your "action"? Or: where is your url pointing to?
as mentioned before: you need some kind of "endpoint" on the serverside:
http://www.springsource.org/
http://www.asp.net/
http://rubyonrails.org/
https://www.djangoproject.com/
http://framework.zend.com/
http://www.catalystframework.org/
http://www.seaside.st/
or whatever