Why does this javascript/jQuery not submit the html form? - javascript

I am trying to submit a HTML based form using Javascript/jQuery, but it seems not to submit anything.
And my HTML form is now;
<form class="navbar-form navbar-right" role="form" id="loginForm" action="login.php">
<div class="form-group">
<input type="text" class="form-control" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="text" class="form-control" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Sign In</button>
</form>
My Javascript code is now;
$(document).ready(function() {
$("#loginForm").submit(function(e) {
e.preventDefault();
var $form = $(this);
var $url = $form.attr('action');
var $username = $("#username");
var $password = $("#password");
if ($username.val().length > 0 && $password.val().length > 0) {
var $posting = $.post(
$url, {
name: $username.val(),
password: $password.val()
}
);
$posting.done(function(data) {
alert("Username: " + data.name + "\nPassword: " + data.password);
});
} else {
alertify.warning("Username or password is empty!");
}
});
})

You have these selectors:
var $username = $("#username");
var $password = $("#password");
But there are no such matching elements in the markup. So this condition will always be false:
if ($username.val().length > 0 && $password.val().length > 0) {
Either change the markup to match the selectors (by adding id="username" and id="password" to the relevant HTML elements), or change the selectors to match the markup:
var $username = $("input[name=username]");
var $password = $("input[name=password]");
Or, even better, as pointed out in a comment below, since the submit handler already has a reference to the form by way of $(this) then you can search on that:
var $username = $form.find("input[name=username]");
var $password = $form.find("input[name=password]");
This can be especially useful given that name doesn't have to be unique in the DOM (though is very often unique in a form).

the issue on your code is that you are not referencing the target input:
<input type="text" class="form-control" name="username" placeholder="Username">
<input type="text" class="form-control" name="password" placeholder="Password">
As you can see, you use name instead of id, if you are using name on your html elements, you need to change this line of your code:
var $username = $('[name="username"]');
var $password = $('[name="password"]'");
But to make your work simpler, just add id attribute on your elements :)
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
<input type="text" class="form-control" name="password" id="password" placeholder="Password">

Related

How to disable submit button until all mandatory fields are filled using html and vanilla js

How to disable submit button until the user enters all fields and also how to use event listener on submit form.
<form action='index.html' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
const init = function () {
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(username,password,email)
};
Jsfiddle link
Set up a validation object with booleans to record if all your values have met validation.
Then I'd loop through all your inputs and add an event listener to each of them. In this example I've checked to see if each has at least one character in them, but you might want to expand on this.
Finally, loop through your validation object and check if all the values are true. If they are, remove the disabled attribute from the button.
let inputs = document.querySelectorAll('input');
let buttonSend = document.getElementById('button-send');
let inputValidator = {
"username": false,
"email": false,
"password": false
}
inputs.forEach((input) => {
input.addEventListener('input', () => {
let name = event.target.getAttribute('name');
if (event.target.value.length > 0) {
inputValidator[name] = true;
} else {
inputValidator[name] = false;
};
let allTrue = Object.keys(inputValidator).every((item) => {
return inputValidator[item] === true
});
if (allTrue) {
buttonSend.disabled = false;
} else {
buttonSend.disabled = true;
}
})
})
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username">
<input type="email" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<button type="submit" name="submit" id='button-send' disabled>SUBMIT</button>
</form>
This is probably not what you are looking for but you can achieve almost the same effect by simply using the required attribute in your input fields:
<form action='index.html' id="form-user">
<input type="text" name="username" id="username" placeholder="username" required>
<input type="email" name="email" id="email" placeholder="email" required>
<input type="password" name="password" id="password" placeholder="password" required>
<button type="submit" name="submit" id='button-send' >SUBMIT</button>
</form>
Using the onBlur event will ensure the user has visited each field. You may also want to check the field contains a value, for that you can add the HTML required attribute.
var isDirty = {
username: false,
password: false,
email: false
}
const init = function() {
let incompleteItems = getIncompleteItems();
if(incompleteItems.length > 0) {
alert(`${incompleteItems} requires a value.`);
return;
}
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let email = document.getElementById("email").value;
alert(`values: ${username}, ${email}, ${password}`);
};
const onChange = function(e) {
isDirty[e.id] = true;
}
const getIncompleteItems = function() {
let incomplete = "";
for (const [key, value] of Object.entries(isDirty)) {
if(value === false) {
if(incomplete.length > 0) {
incomplete += `, ${key}`;
}
else {
incomplete = key;
}
}
}
return incomplete;
}
<form method='GET' id="form-user" onsubmit="init()">
<input type="text" name="username" id="username" placeholder="username" onBlur="onChange(this)">
<input type="email" name="email" id="email" placeholder="email" onBlur="onChange(this)">
<input type="password" name="password" id="password" placeholder="password" onBlur="onChange(this)">
<button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
Create a validation function which will check all the validations and sets the disabled property of the button if validation fails and vice versa. Call the validation function on every change of all the fields.
You can use oninput event
<input type="text" oninput="validate()">

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

PHP & Ajax - how to transfer value of textarea to textbox when value is not empty

I want to transfer the value of my textarea to my textbox automatically when the value of the textbox is fetch. how can I do it? here is my code thank you.
<?php
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
</form>
///////////////////////////////TEXT AREA///////////////////////
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode"></input>
there is my code, so the value comes in the textarea. so when the value is set i want an automatic transfer on the textbox.
I'm not sure what you mean by textbox. If you're wanting to copy the value of the textarea to another element (I'll assume with id='textbox'), do this:
$('#scanned-QR').change(function() {
var textToTransfer = $(this).val(); // get text from textarea
$('#textbox').val(textToTransfer); // set other element's value
});
I assumed that you are trying to transfer the text area value to all input text boxes. And here is the code will transfer data when click on submit.
$('.btn-primary').click(function(){
let scannedQR = $('#scanned-QR').val();
if(scannedQR != '') {
$('input').val(scannedQR);
} else {
alert('please scan the QR code and submit');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" id="card-code" value='sample' class="form-control">
</div>
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='sample2' class="form-control" maxlength="3">
</div>
</form>
<br><br>
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea>
<button class="btn btn-primary btn-lg" type="button" name="btnSubcode">Submit</button>

Trying to Pass Multiple Variables from Multiple Windows through AJAX

I am trying to pass multiple variables from two different windows into the same PHP script. Is this possible? If not, what would be the best course of action?
Thanks
verifyemail.html
<script type = "text/javascript" src = "js/js_functions.js"> </script>
<form method="post" onsubmit = "return testAjax();" />
<input type="email" placeholder="email" name="email" required maxlength = "50"><br>
<input type="email" placeholder="re-enter email"name="reemail" required maxlength = "50"><br>
<input type="submit" value="Verify Email">
</form>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
signup.html:
<script type = "text/javascript" src="js/js_functions.js"></script>
<form method="post" onsubmit="return ajaxTest();"/>
<input type="text" placeholder="username" name="username" required = "required" maxlength = "15"><br>
<input type="password" placeholder="password" name="password" required = "required" pattern = "(?=.*\d)(?=.*[A-Z]).{10,}"><br>
<input type="password" placeholder="re-enter password"name="repassword" required = "required"><br>
<p class = "passwordreq">Password must:</p>
<input type="submit" value="sign up"> <input type="button" value="go back" onclick="window.location='index.html'">
</form>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
js_functions
var username, password;
function setUsrandPass(form)
{
if(form.password.value != form.repassword.value)
{
alert("Passwords do not match");
}
else {
username = form.username.value;
password = form.password.value;
window.location = 'verifyemail.html';
}
return false;
}
function ajaxTest()
{
if(form.email.value != form.reemail.value)
{
alert("Emails do not match");
}
else
$.ajax({
type: 'GET',
url: 'signup_script.php',
data: {usr: username, pass: password, em: form.email.value},
});
return false;
}
php script:
<?php
include 'profile_Functions.php';
$username = $_GET['usr'];
$password = $_GET['pass'];
$email = $_GET['em'];
echo "got here!";
createUser($username,$password,$email);
?>
This is not possible with things from separate pages. They need to be making the same request to the PHP script to provide both data.
You may be able to circumvent this by writing with PHP to some sort of datastore, i.e. a file or a database, then you wait for the other script to write as well, and then PHP can do any processing it needs.

display a div based on url parameter

My website is trackschoolbus.com. You can see a login form at the top right. What I have set up is when a wrong input is given it redirects to home page with a parameter as ?er=1 i.e. http://www.trackschoolbus.com/?er=1.
I need to display a error message when the error url comes so I have written
<script type="text/javascript">
$(function(){
if (document.location.href.indexOf('er=1') > 0)
$("#display").show();
});
</script>
and the html is
<div id="display" style="display:none;">wrong input</div>
my login form is
<form name="login-form" id="login-form" method="post" action="http://www.trackschoolbus.com/vehicleTracking/index.php">
<input name="LoginForm[username]" id="LoginForm_username" type="text" placeholder="Registered Email" value="" class="error" required/>
<input maxlength="30" name="LoginForm[password]" id="LoginForm_password" type="password" placeholder="Password" value="" class="error" required />
<input type="submit" onclick="this.disabled=true;this.form.submit();" name="yt0" class="btn-submit" value="Login" />
</form>
still it shows display none.
use php
<form name="login-form" id="login-form" method="post" action="http://www.trackschoolbus.com/vehicleTracking/index.php">
<input name="LoginForm[username]" id="LoginForm_username" type="text" placeholder="Registered Email" value="" class="error" required/>
<input maxlength="30" name="LoginForm[password]" id="LoginForm_password" type="password" placeholder="Password" value="" class="error" required />
<input type="submit" onclick="this.disabled=true;this.form.submit();" name="yt0" class="btn-submit" value="Login" />
<?php if (isset($_GET['er']) && $_GET['er'] == 1) {
echo '<div id="display">wrong input</div>';
}?>
</form>
You can use this code
if ($_REQUEST['er']==1)
{
echo '<script type="text/javascript">
$("#display").show();
</script>';
}
This is relatively simple in javascript.
Using the code snippet in this thread: How can I get query string values in JavaScript?
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if (getParameterByName("er") == "1")
$("#display").show();
});

Categories