Check an array of values with jQuery - javascript

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 });
}
}
});

Related

Trying to stop duplicate values being entered twice

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>

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");
}
}

I need to create a new user and password in my object

I need to create a new username and password in my object, when I type it in my text input,after that i need to check it, if they are equal to my username and password in my array object, so the message be YOURE IN, if not equal you need to display message THE PASSWORD OR THE USERNAME IS THE SAME,PLEASE TAKE ANOTHER USERNAME.
When you create a new password & username, I need to added it to the array,after that I need to type it,and if its equal,so i logged in,but I can't make it good,I almost thinking how it works,why when I clicked the button,the function is not works,but in the console I don't see a errors.
window.onload = function(){
document.getElementById("myButton").addEventListener("click", sys.addUser());
var newUser = myUser.value;
var newPass = myPassword.value;
};
var sys = {
users:[
{username: "alexandr", password:"1334"},
{username: "evgeny", password:"1345"},
],
addUser: function(username, password){
var same = false;
for(var x = 0; x < sys.users.username && sys.users.password; x++){
if( newUser.length == this.users.username.length[x]){
same = true;
if(same == true){
myMessage.innerHTML ="Its a same";
}
else if(newPass.length == this.users.password.length[x]){
same = true;
myMessage.innerHTML ="Its a same";
}
else{
this.users.username.push(newUser);
myMessage.innerHTML = "Ok";
}
}
}
}
};
You can use some() method to check if some object has the same password or input as your input values.
var sys = {
users: [{
username: "alexandr",
password: "1334"
}, {
username: "evgeny",
password: "1345"
}],
addUser: function() {
var myUser = document.getElementById('myUser').value
var myPassword = document.getElementById('myPassword').value
// This will check if object with same username and password exists in array
var check = this.users.some(function(e) {
return e.username == myUser && e.password == myPassword
})
console.log(check ? 'Correct' : 'Wrong username or password.')
}
};
// You need to use bind here so that context of this in your method is that object and not element on which you are calling event listener
document.getElementById("myButton").addEventListener("click", sys.addUser.bind(sys));
<input type="text" id="myUser">
<input type="text" id="myPassword">
<button id="myButton">Check</button>
Going by your code logically, you are checking the length while you must check on contents.
For example, sunils will match with evgeny even though they are different.
Have this:
newuser == users.username[x] instead
There's a lot of errors there, working with your code as it is I turned it into this. Use a code diff tool to see all the changes
As you say, this is a learning exercise so I figured that correcting your code would be of more use to you than showing you a better way to do this.
In the future you'd be well advised to use jsfiddle to come up with a semi working example for people to play with
<html>
<body>
<button type=button id=myButton>click me</button>
<input type="text" id='myUser'/>
<input type="text" id='myPassword'/>
<span type="text" id='myMessage'></span>
<script>
var sys = {
users: [
{ username: "alexandr", password: "1334" },
{ username: "evgeny", password: "1345" },
],
addUser: function (username, password)
{
newUser = document.getElementById("myUser").value;
newPass = document.getElementById("myPassword").value
myMessage = document.getElementById("myMessage")
var same = false;
for (var x = 0; x < sys.users.length; x++)
{
if (newUser.length == sys.users[x].username.length)
{
same = true;
if (same == true)
{
myMessage.innerHTML = "Its a same";
}
else if (newPass.length == sys.users[x].password.length)
{
same = true;
myMessage.innerHTML = "Its a same";
}
}
}
if (!same)
{
sys.users.push({ username: newUser, password: newPass });
alert(sys.users.length);
myMessage.innerHTML = "Ok";
}
}
};
window.onload = function(){
document.getElementById("myButton").addEventListener("click", sys.addUser);
};
</script>
</body>
</html>

How to return name values of empty fields in jQuery

I have this piece of code that validates an html form and highlight empty fields with red borders.
What I want is to be able to return the name values of empty input fields so I can output them.
var isValid = $('input, textarea').not('input:disabled').filter(function() {
return !this.value;
}).css('border-color', 'red').length == 0;
if(isValid){
console.log('Ok');
}else if(!isValid){
console.log($(this).attr('name') + 'must not be empty');
}
When there are no empty fields the first part works well, but when there are empty fields I was expecting to get the name values of those inputs in the console. But I keep getting undefined
Can use map()
var isValid = $('input, textarea').not('input:disabled').filter(function() {
return !this.value;
}).css('border-color', 'red')
var names = isvalid.map(function(){
return this.name;
}).get()
The reason is that isValid is boolean (.length == 0). You need to get the filtered elements like this:
var isValidEl = $('input, textarea').not('input:disabled').filter(function() {
return this.value.length == 0;
}).css('border-color', 'red');
And then, change the condition to:
if(!isValidEl.length){
console.log('Ok');
} else {
isValidEl.each(function() {
console.log($(this).attr('name') + ' must not be empty');
});
}
Exmaple:
var isValidEl = $('input, textarea').not('input:disabled').filter(function() {
return this.value.length == 0;
}).css('border-color', 'red');
if(!isValidEl.length){
console.log('Ok');
} else {
isValidEl.each(function() {
console.log($(this).attr('name') + ' must not be empty');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" name="emptyInput">
<textarea name="emptyTextaria"></textarea>
<textarea name="nonEmptyTextaria">HELLO</textarea>
<input type="text" value="HELLO" name="nonemptyInput">

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