Im new to javascript and i have this kind of problem. I have two fields and they must be checked if the input inside is the same. If they are the same an alert should popup to tell so. Thanks in advance.
Here is an example of my fields:
function writeText() {
n = "has been collected " + window.document.myform.exemplu1.value;
document.getElementById("content").innerHTML = n;
}
function writePass() {
n = window.document.myform.exemplu2.value;
alert("password is " + n);
}
<div>
<h3> Example</h3>
<form name="myform">
<p> <input name="exemplu1" type="text" value="Edit field" onBlur="writeText()" size="25" maxlength="30" />
<span id="content"> </span></p>
<p> <input name="exemplu2" type="password" value="Parola" onBlur="writePass()" size="15" maxlength="15" /></p>
</form>
</div>
Use the strict equality operator.
I have bound a callback using adEventListener to the click event of a button to perform the check.
const buttonEl = document.querySelector('button')
const usernameEl = document.getElementById('username')
const passwordEl = document.getElementById('password')
buttonEl.addEventListener('click', () => usernameEl.value === passwordEl.value ? console.log('They are the same') : console.log('They are different'))
* {
color: #DDD;
background-color: white;
font-size: 1.1em;
padding: 10px;
margin: 10px;
}
<input type="text" id="username" />
<input type="password" id="password" />
<button>Check</button>
Related
If I enter the exact number of 300000, the form is submitted. Any other value below or above 300000 causes the error message to display. The error message should only display when the value is less than 300000. What's the error in my code?
document.addEventListener("DOMContentLoaded", function() {
document.querySelector('#sbutton').addEventListener('click', function(event) {
event.preventDefault();
let inputV = document.querySelector('#budget').value.trim();
let budgetRegex = /^3[0-9]{5,}/;
const errorMessage = document.querySelector('#errormsg');
let form = document.querySelector("form");
if (inputV == "" || !budgetRegex.test(inputV)) {
errorMessage.innerHTML = "Value should be at least 300,000.";
errorMessage.style.display = 'block';
} else {
errorMessage.innerHTML = "";
errorMessage.style.display = 'none';
form.submit();
}
});
});
<form action="https://dragonmm.xyz" method="post">
<div class="contact-box">
<div class="left1"></div>
<div class="right1">
<h2>Start</h2>
<label for="name"></label>
<input id="name" type="text" class="field" placeholder="Name" required>
<label for="email"></label>
<input id="email" type="text" class="field" placeholder="Email" required>
<label for="phone"></label>
<input id="phone" type="text" class="field" placeholder="Phone" required>
<label for="budget"></label>
<input id="budget" type="text" name="budget" class="field budgetInput" placeholder="Budget" required>
<div id="errormsg"></div>
</div>
</div>
<button type="submit" value="Send" class="btn1" id="sbutton">Send</button>
</form>
Use a numeric input field (type="number"). Use the min attribute of the field to limit the input (although a user can still input her own text). Next, convert values to Number, so you can do calculations.
Here's a minimal example, using event delegation.
Finally: you should always check values server side too.
document.addEventListener(`input`, handle);
function handle(evt) {
if (evt.target.id === "budget") {
if (+evt.target.value < +evt.target.min) {
// ^convert to Number
return document.querySelector(`#budgetError`)
.classList.remove(`hidden`);
}
return document.querySelector(`#budgetError`)
.classList.add(`hidden`);
}
}
#budgetError {
color: red;
}
.hidden {
display: none;
}
<input id="budget" type="number" min="300000"> budget
<div id="budgetError" class="hidden">
Not enough! We need at least 300,000</div>
I have a form in my HTML that takes in first name, last name, and phone number to create an account ID. The input textboxes for first name, last name, and account ID accept keyboard input and display it, as would be expected. However, when I'm viewing the page on the Firefox browser, only the phone number textbox doesn't work. I can click into the box once and see the cursor, but as soon as I start typing, no text shows up, and the cursor disappears. However, based on the Javascript creating an account ID with the last four digits of the phone number typed, I know the input is recognized. It works in other browsers, just not in Firefox.
<article>
<h2>New Account Information</h2>
<form>
<fieldset id="deliveryinfo">
<label for="fnameinputacct">First Name</label>
<input type="text" id="fnameinputacct" name="fname" />
<label for="lnameinputacct">Last Name</label>
<input type="text" id="lnameinputacct" name="lname" />
<label for="phoneinputacct">Phone Number</label>
<input type="text" id="phoneinputacct" name="phone" />
<label for="accountidbox">Account ID</label>
<input type="text" id="accountidbox" name="accountid" />
</fieldset>
<fieldset id="submitbutton">
<input type="submit" id="submitBtn" value="Create Account" />
</fieldset>
</form>
</article>
Here is the CSS
fieldset {
margin-bottom: 10px;
position: relative;
padding: 2.5em 1em 0.5em 1em;
background: #e3d5ba;
}
#deliveryinfo label {
display: block;
float: left;
clear: left;
margin-top: 5px;
}
#deliveryinfo input {
display: block;
margin-left: 130px;
}
#fnameinputacct, #lnameinputacct, #phoneinputacct, #accountidbox {
width: 12em;
}
#submitBtn {
font-size: 1.25em;
}
And some Javascript that goes with the fields. This method is added in another function.
function createID() {
var fname = document.getElementById("fnameinputacct");
var lname = document.getElementById("lnameinputacct");
var phone = document.getElementById("phoneinputacct");
var account = document.getElementById("accountidbox");
var fields = document.getElementsByTagName("input");
var acctid;
var fistInit;
var lastInit;
if (fname != "" && lname != "" && phone != "") {
fistInit = fname.value.charAt(0).toUpperCase();
lastInit = lname.value.charAt(0).toUpperCase();
acctid = fistInit + lastInit + phone.value.substring(phone.value.length - 4);
account.value = acctid;
newAccountArray = [];
for (var i = 0; i < fields.length - 1; i++) {
newAccountArray.push(fields[i].value);
}
}
}
You might try breaking up your form field groups with a <div> or <p>.
See https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form
Some of the widely used css frameworks do this as well. Look at Semantic UI, Bootstrap, or Material. These do a similar grouping with div containers for each label/input
Example from semantic ui form:
<form class="ui form">
<div class="field">
<label>First Name</label>
<input type="text" name="first-name" placeholder="First Name">
</div>
<div class="field">
<label>Last Name</label>
<input type="text" name="last-name" placeholder="Last Name">
</div>
<div class="field">
<div class="ui checkbox">
<input type="checkbox" tabindex="0" class="hidden">
<label>I agree to the Terms and Conditions</label>
</div>
</div>
<button class="ui button" type="submit">Submit</button>
</form>
I have used pure JavaScript to validate this login form consider the below example and also check out the live demo here https://codepen.io/uicreation/pen/xpdbKe
hope it will be help you to understand how JavaScript validation is works.
Live Demo
if(document.getElementsByClassName('firstForm')[0]){
document.getElementsByClassName('firstForm')[0].onsubmit = function(e){
e.preventDefault();
var field = this;
var email = field.querySelector('input[type=email]');
var pass = field.querySelector('input[type=password]');
var 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,}))$/;
if(!regex.test(email.value)){
console.log("enter a valid email address")
} else if(pass.value.length < 8){
console.log("password should be greater than 8 characters")
} else {
console.log("success!")
}
}
}
form {
margin: 30px 0 0 30px;
}
fieldset {
padding:5px;
}
label {
min-width:60px;
display: inline-block;
}
input[type=submit]{
margin-top:5px;
margin-left:5px;
}
<form class="firstForm" novalidate>
<fieldset>
<label>Email</label>
<input type="email" name="email" placeholder="Enter Email" />
</fieldset>
<fieldset>
<label>Password</label>
<input type="password" name="password" placeholder="Enter Password" />
</fieldset>
<input type="submit" value="Login" />
</form>
I've this small form in which the 1st field(title) is required by default. The 2nd and the 3rd are required only in a specific condition.
Case-I: If tool name is filled out, both tool name & tool URL become required.
Case-II: If tool URL is filled out, both tool name & tool URL become required.
I'm not sure it is working as expected.
Could you please help me correct my code?
$(document).ready(function(){
articleTitle = $('#title').val();
toolName = $('#toolName').val().trim();
toolURL = $('#toolURL').val();
if(((toolName.length>0)&&(toolURL==="")) || ((toolName.length<=0)&&(toolURL!==""))){
$('#toolName').prop('required', true);
$('#toolURL').prop('required' , true);
} else {
$('#toolName').prop('required', false);
$('#toolURL').prop('required', false);
}
$("#myForm").submit(function(){
sayHello();
return false;
});
});
label {
float: left;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
You can simplify your code quite a bit, please see the comments for a description.
var $toolName = $('#toolName')
var $toolURL = $('#toolURL')
var $toolInputs = $($toolName).add($toolURL)
function sayHelloToMyLittleFriend() {
alert('sup! form was submitted')
}
$toolInputs.on('change', function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
$toolInputs.prop('required', toolName || toolURL)
})
$('form').submit(function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
var bothFilled = !!toolName && !!toolURL
var noneFilled = !toolName && !toolURL
if (bothFilled || noneFilled) {
sayHelloToMyLittleFriend()
return true
}
return false
})
label {
float: left;
width: 100px;
}
/* this will show what element has the required attribute */
[required] {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
Here is a straightforward approach using library-less javascript (rather than jQuery).
(Albeit, you'll see that it's very similar to the jQuery).
Whenever data is entered into or removed from the form, the form inputs are checked and, as appropriate, the required attributes are added or removed.
var myForm = document.getElementById('myForm');
var toolName = document.getElementById('toolName');
var toolURL = document.getElementById('toolURL');
function checkInputs() {
if ((toolName.value !== '') || (toolURL.value !== '')) {
toolName.setAttribute('required','required');
toolURL.setAttribute('required','required');
}
if ((toolName.value === '') && (toolURL.value === '')) {
toolName.removeAttribute('required');
toolURL.removeAttribute('required');
}
}
myForm.addEventListener('keyup', checkInputs, false);
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<input type="submit" value="Submit" />
</form>
i have some code that works for a password form where the user is filling out their details and then 2 of the boxes only work or become typable if they enter a number/age greater than that specified. i now want to take it one step further and make it obvious to the user that those boxes are only editable certain times by colouring them in a different colour. for some reason though the new code within the JS is not working.
code is below:
<div class="container">
<div class="jumbotron" id="firstform">
<h1>Sign up page</h1>
<form id="myform">
<label>Username </label> <input type="text" name="uname" id="uname" data-placement="bottom" title="" data-original-title="Username must be unique" class="mytooltip"><br>
<div class="pwordCheck">
<label>Password </label> <input type="password" id="pword" data-placement="bottom" title="" onkeyup="passwordValidation(); return false;" data-original-title="Password must be more than 6 characters long" class="mytooltip"><br>
<label>Confirm Password </label> <input type="password" id="confpword" onkeyup="passwordValidation(); return false;" data-placement="bottom" title="" data-original-title="Passwords must match" class="mytooltip">
<span id="themessage" class="themessage"></span><br>
</div>
<label>Email </label> <input type="email" id="e-mail"><br>
<label>Age </label> <input type="number" id="age" oninput="ifOfAge(); return false;"><br>
<label>Can you drive? </label> <input type="text" id="drive" disabled><br>
<label>What is your occupation? </label> <input type="text" id="occupation" disabled><br>
<input type="submit" value="Submit" onclick="usernameAlreadyExists(); return false;">
</form>
</div>
</div>
css:
input#drive{
background-color: #999;
}
input#occupation{
background-color: #999;
}
js:
function ifOfAge() {
var age = document.getElementById("age");
var drive = document.getElementById("drive");
var occupation = document.getElementById("occupation");
var white = "#fff";
if (age.value >= 21) {
drive.disabled = false;
occupation.disabled = false;
} else if (age.value >= 16) {
drive.disabled = false;
occupation.style.backgroundColor = white;
} else {
drive.disabled = true;
occupation.disabled = true;
drive.style.backgroundColor = white;
occupation.style.backgroundColor = white;
}
}
Color must be enclosed within quotes. Like below. Wherever you have used white surround it with quotes
drive.style.backgroundColor = "white";
you can make change color for disabled input like this.
EDIT
function ifOfAge() {
var age = document.getElementById("age");
var drive = document.getElementById("drive");
var occupation = document.getElementById("occupation");
var white = "#fff";
if (age.value >= 21) {
drive.disabled = false;
occupation.disabled = false;
} else if (age.value >= 16) {
drive.disabled = false;
occupation.style.backgroundColor = white;
} else {
drive.disabled = true;
occupation.disabled = true;
drive.style.backgroundColor = "#999";
occupation.style.backgroundColor = "#999";
}
}
You can make it more nice if you used jQuery and plugin jQuery Validation or even more nice with this one.