Trying to stop duplicate values being entered twice - javascript

Trying to stop the same value(s) being submitted twice. I have created an function which allows a user to enter a name and a mark to be submitted to a simple site i am trying to create. If the same value(s) (name & mark) are entered I am trying to figure out a way to alert the user and stop the name and mark being submitted to the console.
function add() {
name.push(nameInput.value);
mark.push(markInput.value);
if (name == "" && mark == "") {
document.getElementById("result").innerHTML = "No name or mark Has Been Entered. Please Try Again!";
} else if (name && mark) {
document.getElementById("result").innerHTML = "Name & Mark has successfully been entered!";
console.log(name, mark);
} else if (name == mark) {
var n = name.includes("Ross", 0);
//console.log(name, mark);//
}
}
document.getElementById("Add").addEventListener("click", insert);

You should move name.push(nameInput.value); mark.push(markInput.value); into block where it satisfies the criteria of inserting.Here the criteria is values should not be empty and they should be unique.
if (!name && !mark ) {
document.getElementById("result").innerHTML = "No name or mark Has Been Entered. Please Try Again!";
}
else if (names.includes(nameInput.value) && mark.includes(markInput.value)) {
document.getElementById("result").innerHTML = "Name & Mark are same please enter again!";
}
else{
names.push(nameInput.value);
marks.push(markInput.value);
document.getElementById("result").innerHTML ="Name & Mark has successfully been entered!"
}
Alternatively you can also use object to achieve this.
Create an object having the name and mark as properties
let person = {name: name.value,mark: mark.value };
and push the object into the arr.
To check if the same name and mark are submitted use arr.find().
let name = document.getElementById("name");
let mark = document.getElementById("mark");
let arr = [];
const add = () => {
if (!name.value || !mark.value) {
alert("Please enter the value in both fields");
return;
}
let person = {
name: name.value,
mark: mark.value
};
if (arr.find(personIn => personIn.name == person.name && personIn.mark == person.mark)) {
alert("Please dont repeat the values");
return;
}
arr.push(person);
}
document.getElementById("submit").addEventListener('click', add);
Name:<input type="text" id="name" /><br> Mark:
<input type="text" id="mark" /><br>
<button id="submit">Submit</button>

Related

How do I find out if a input element's value is blank (null)

I have following code to check if the inputs with the ids emailForm and nameForm are blank, this however isn't working when I test the form by leaving it blank.
function setInfo() {
if (document.getElementById("emailForm").value == null ||
document.getElementById("nameForm").value == null) {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Could someone help me with this, thanks!
Instead of checking for null specifically, you should check for falsy values. In some cases, the values for empty textboxes will be an empty string.
Replace this:
if (document.getElementById("emailForm").value == null || document.getElementById("nameForm").value == null) {
with this:
if (!document.getElementById("emailForm").value || !document.getElementById("nameForm").value) {
You shouldn't be checking whether the fields are null, you should be checking whether they content is an empty string (with .value == '').
This can be seen working in the following:
function setInfo() {
if (document.getElementById("emailForm").value == '' ||
document.getElementById("nameForm").value == '') {
console.log("Please fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
//loaded();
console.log("All sections filled in");
}
}
const button = document.getElementById('go');
button.addEventListener('click', function() {
setInfo();
});
<input id="emailForm" />
<input id="nameForm" />
<button id="go">Go</button>
Make sure you calling function setInfo()
function setInfo() {
// You can check Value.Length also or
if (document.getElementById("emailForm").value === "" ||
document.getElementById("nameForm").value === "") {
alert("Please Fill in all sections");
} else {
email = document.getElementById("emailForm").value;
name = document.getElementById("nameForm").value;
loaded();
}
}
Try below solution:
function setInfo() {
var email=document.getElementById("emailForm").value;
var name=document.getElementById("nameForm").value;
if (email=='' || email==null || name=='' || name== null ) { // OR if (!email || !name)
alert("Please Fill in all sections");
return;
} else {
loaded();
}
}
You should check whether the string is empty or not instead of null. Try using the code below:
function setInfo() {
var a=document.getElementById("emailForm").value;
var b=document.getElementById("nameForm").value;
if (a == "" ||
b == "") {
alert("Please Fill in all sections");
} else {
email =
document.getElementById("emailForm").value;
name =
document.getElementById("nameForm").value;
alert("success alert");
}
}

Either Can Not submit(); form in jQuery, or can not check if input fields are filled out

I am having trouble submitting the below form.
For background, I'm trying to "submit" a form for a delivery, and I need to know a) their pickup address, b) their dropoff address, and c) their description. I created <p class="error"> fields if those <input>s are empty (as in "Please enter a description").
If I remove the 'return false;' the form submits no matter what, but if I keep the 'return false;' the jQuery works (i.e. - error message appears) but now the form NEVER submits. Thoughts?
Here's my main.js
var main = function() {
$('form').submit(function() {
var pickup = $('#pickup').val();
if(pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if(dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if(description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
return false;
});
};
$(document).ready(main);
var main = function () {
$('form').submit(function () {
var pickup = $('#pickup').val();
if (pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if (dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if (description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
// did not pass validation
if (pickup != "" || dropoff != "" || description != "") {
return false;
}
// passed validation, submit
return true;
});
};
$(document).ready(main);

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

Check an array of values with jQuery

Hi I'm trying to loop and check an array with specific values. If the value already exists that the user want to use in the input a message will be displayed, if the username is a correct one and new it will be uploaded to my firebase! It works for the first element in the array but if i set .length in the loop it takes all but sends the false value anyway?
<form id="">
<label>Your username: </label><input type="text" id="userName">
</form>
<script src="text/javascript">
var invalidUser=['value1','value2','value3','value4'];
var myDataRef = new Firebase('https://leastflyingwasps.firebaseio.com/');
$('#userName').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#userName').val();
for (var i = 0;i<invalidUser;i++) {
}
if (invalidUser[i] === name) {
alert('Not a valid username')
}
else {
myDataRef.push({name: name});
}
}
});
</script>
The first issue is because your check is actually happening outside of the for loop. Secondly, you could simplify this by using $.inArray():
var invalidUser = ['value1', 'value2', 'value3', 'value4'];
$('#userName').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#userName').val();
if ($.inArray(name, invalidUser) != -1) {
alert('Not a valid username')
}
else {
var myDataRef = new Firebase('https://leastflyingwasps.firebaseio.com/');
myDataRef.push({ name: name });
}
}
});

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories