I don't know what im doing wrong, i have a form and using this function to check if the input is empty...what Iam trying to do is to highlight the field by adding a class to the text field...but if i add this line
name.addClass("empty");
to the function, the function dont work
function register()
{
if(document.myForma.userid.value == '')
{
name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required")
name.addClass("empty");
return false;
}
}
Declare your name variable as local, or use a different name for it, - global window.name already exists and is not changeable.
console.log(name);
function register() {
if (document.myForma.userid.value == '') {
var name = $("#userid");
document.myForma.userid.focus();
$("#empty").html("This field is required");
name.addClass("empty");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForma" name="myForma" onsubmit="return register();">
<input id="userid" type="text" />
<div id="empty"></div>
<input type="submit" />
</form>
Related
I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn.
I have disabled submit button using javascript like this
document.getElementById("submit-btn").disabled = true;
Now I am looking for allow submit if both of my fields are filled.
My full javascript is like this
<script type="text/javascript">
document.getElementById("submit-btn").disabled = true;
document.getElementById("submit-btn").onclick = function(){
window.open("https://google.com",'_blank');
}
</script>
I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same.
Thanks!
Id propose something like this
Use a block, which encapsulates the names of variables and functions inside the block scope
Make small functions, which do just one thing
Prefer addEventListener over onclick or onanything
There are two types of events you could use on the inputs: input and change. input will react on every keystroke, check will only react, if you blur the input element
I added a check for validity to the email field with checkValidity method
{
const btn = document.getElementById("submit-btn");
const fname = document.getElementById("fname");
const email = document.getElementById("email");
deactivate()
function activate() {
btn.disabled = false;
}
function deactivate() {
btn.disabled = true;
}
function check() {
if (fname.value != '' && email.value != '' && email.checkValidity()) {
activate()
} else {
deactivate()
}
}
btn.addEventListener('click', function(e) {
alert('submit')
})
fname.addEventListener('input', check)
email.addEventListener('input', check)
}
<form>
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="submit-btn" value="Submit">
</form>
This is the simplest solution I can imagine:
myForm.oninput = () => {
btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
<input type="text" name="" id="fname">
<input type="email" name="" id="email">
<input type="submit" id="btn" value="Submit" disabled>
</form>
Personally, I prefer to use regex to check the e-mail, instead of checkValidity(). Something like this:
/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);
I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.
I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>
The problem is that I can't get value of my password fields - alert with pso1 returns null.
I don't see any error in this code so I'm asking for help.
<form class='container' onsubmit="return checkit()">
<h1> Javascript </h1>
Login <input type='text' id='log'><br>
Password <input type='password' id='pso1'><br>
Confirm passwordd <input type='password' id='pso2'><br>
<button>Register</button>
</form>
<script type="text/javascript">
var pso1=document.getElementById('pso1').value ;
var pso2=document.getElementById('pso2').value ;
alert(pso1);
function checkit(){
if(pso1=!pso2){
return false;
alert('Passwords are not the same.');
}
else{
return true;
alert('work');
}
}
</script>
</body>
In your code you are setting the values of pso1 and ps02 once right after the page load before their values are changed. You will want to update these values instead, declared them as local variables inside your function:
function checkit(){
var pso1=document.getElementById('pso1').value;
var pso2=document.getElementById('pso2').value;
if(pso1=!pso2){
return false;
alert('Passwords are not the same.');
}
else{
return true; alert('work');
}
}
You have only declared the function checkIt. You need to call that function to actually check it.
I am using javascript and I want to change an html code based on what is in the text box. But I have values that are passed from the previous page and put into the inputs. But the html code does not trigger because it uses a .keyup function and I want to know if it was possible to execute javascript without a keyup function and without altering the text.
My code
<div>
<label>Name</label><br />
<input type="text" id="name" name="name" onChange="NameCheck();"/>
<span class="error" id="namecheck"></span>
</div>
$(document).ready(function () {
$("#name").keyup(NameCheck);
});
function NameCheck() {
var password = $("#name").val();
if (password == ""){
$("#namecheck").html("Name is Blank");
$("#namecheck").css('color', 'red');
return false;
}else{
$("#namecheck").html("Name Is Valid");
$("#namecheck").css('color', 'green');
return true;
}
}
Check this jsfiddle, it is a working example of what you want! note that you don't need the onchange method, because your using jquery's keyup
so your code should be like this:
JS:
$(document).ready(function () {
$("#name").keyup(function () {
NameCheck();
});
NameCheck();
});
function NameCheck() {
var password = $("#name").val();
if (password == "") {
$("#namecheck").html("Name is Blank");
$("#namecheck").css('color', 'red');
} else {
$("#namecheck").html("Name Is Valid");
$("#namecheck").css('color', 'green');
}
}
HTML:
<div>
<label>Name</label>
<br />
<input type="text" id="name" name="name" />
<span class="error" id="namecheck"></span>
</div>
Though you should really restructure your code to not use globals, if you want to call NameCheck() on page load just call it after your event binding, like:
$(document).ready(function () {
$("#name").keyup(NameCheck);
NameCheck();
});