Correct syntax for IF statement - javascript

Can anyone tell me why this IF statement doesn't work, please? I'm using jQuery and Firebug but the latter is not giving me any useful information.
I'm simply attempting to reveal a "submit" button when all of the fields have been completed and the script runs every couple of seconds to check for input.
My code excerpt goes a little like this:
function checkForm(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
// The following line shows me that the values for the fields are all getting picked up properly
$('#report').html("userName: "+userName+"<br />userContent: "+userContent+"<br />userEmail: "+userEmail);
// But the following line is throwing some kind of error
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideDown();
} else {
$('#update').slideUp();
}
}
$(document).ready(function(){
$('#update').hide();
setInterval('checkForm()' , 2000);
});
And my HTML...
<div id="report"></div>
<form id="submitfact">
<div id="update">Update Database</div>
<label><input id="name" name="name" type="text" value="" /><span>Fact submitter's name</span></label>
<label><input id="email" name="email" type="text" value="" /><span>Fact submitter e-mail address</span></label>
<label class="content"><span>Fact text</span><br /><textarea id="content" name="content"></textarea></label>
</form>
Edit...
I apologise if people think I'm wasting their time by not providing the error message - but Firebug simply isn't giving me anything useful - if it was I'd be posting it here. I am a reasonably experienced php programmer but fairly new to jQuery so I admit I am still getting to grips with both writing the language and debugging it. I'd like to post a screen shot of Firebug's response but, as a new user, I am not allowed... all I am getting is a "red error circle/yellow play triangle" icon in the line numbers column ("script" tab) on the line I've shown above... there is nothing else unless you can tell me where else to look other than the "script" and "console" panels?
Another edit...
Well, I got it fixed by taking a look at Cristoph's suggestion. It's basically the same solution but instead of calling it as a function I put it "inline". I'm not entirely sure what the difference between the two techniques is or whether it's simply a local issue I was having but my new jQuery looks like this:
$(document).ready(function(){
$('#submitfact').keyup(function(){
var userName = $('#name').val();
var userContent = $('#content').val();
var userEmail = $('#email').val();
$('#report').html(userName + "<br />" + userContent + "<br />" + userEmail);
if (userName == "" || userContent == "" || userEmail == ""){
$('#update').slideUp();
} else {
$('#update').slideDown();
}
});
});
I will have a look through your other comments to see if I can streamline it at all but at least I have a working baseline now! Thanks for your time, everyone :)

First of all, is it really throwing an error, or is it simply not working?
From how i understand your code, your if condition should be:
if (!userName === "" && !userContent === "" && !userEmail === ""){
// show
$('#update').slideDown();
} else {
// hide
$('#update').slideUp();
}
Second: doing this with a timer is a bad idea.
Introducing an eventhandler to check once an inputvalue changed is far better:
$("input").change(function(){
// if all inputs are filled, show Button, else hide it
});
P.S.
advanced insight into Javascript: an empty string is considered "falsy", thus
username === "" could be written as !username. Note however, that undefined, null, false, 0 and NaNare also considered "falsy"! THis means, you can't distinguish them. For this reason i prefer username === "" ( note the === ! )

Try changing your evaluation to this:
if (!userName || !userContent || !userEmail){
$('#update').slideDown();
} else {
$('#update').slideUp();
}

Related

How to check if the text is missing a certain character?

The task that I'm working on has an div where you need to input your email. It's a simple task, it only needs to check if the email is missing # and a period, and then display certain text, nothing too complicated. But, I've tried using the includes() function and the Chrome Console thing displays an error saying that varname.includes() it's not a function.
Here's part of my HTML code where the JavaScript should take place after using onlick:
<div class="warning"> </div>
<div class="email">
<input class="mail" type="email" name="mail" placeholder="your email">
<input class="send" type="submit" name="send" value="SEND" onclick="checkEmail()">
</div>
Bascially, what the JavaScript code needs to do is:
If it's missing #, write "missing #" in the warning div.
If it's missing ., write "missing ." in the warning div.
If it's missing both # and ., write "Your email address is not correct!" in the warning div.
If the email meets both criteria, it makes an alert saying "You are in!"
As I mentioned, I tried using includes() within an if, which didn't work, and I have no clue what else would work here. I know basics like how to make an alert or write text, I just don't know how to make the code check if the characters are there or missing. Any help on this would be greatly appreciated!
const toCheckFor = ["#", "."] // Array of all characters to check for
const text = "whatever you want" // text you want to check in
let flag = true // flipped to false if one character in the array not found
toCheckFor.forEach(e => {
flag &= text.includes(e)
})
Flag will be true if the text contains all characters in toCheckFor.
Here is an example based on your post ...
const mail = document.querySelector('input[name="mail"]'); // cache for later use
const warning = document.querySelector('.warning'); // cache for later use
function checkEmail() {
const error = {};
const text = mail.value;
if (!text.includes('#') && !text.includes('.')) {
warning.textContent = 'Your email address is not correct!';
return; // end here
}
/*
this is a shorthand
you can also write
if (!text.includes('#')) {
error.push('missing #');
}
*/
!text.includes('#') && error.push('missing #');
!text.includes('.') && error.push('missing .');
if (!error[0]) { // there are some errors
warning.textContent = error.join(' & ');
}
else { // no error
warning.textContent = "You are in!";
}
}
I suggest you'd better use regex check against the input email address by the following function:
function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(String(email).toLowerCase());
}

How can I make a js function recognize a clicked or empty checkbox?

I'm modifiying an existing form.
You can launch a task block with several fields, and if these are all empty, you can remove the block again. Most of them are required, to submit as data complete. If not complete, you can save Work in Process (sic! I'd have preferred Work in Progress...)
For the code to recognize empty fields, it seems that most of them have value="". When completed, the system seems to to recognize that they are not empty.
But the Checkbox I want to use causes problems.
If I don't set value="", it's not recognized as empty, and I can't remove the block.
If I set value="" , it's not recognizing an entered checkmark, and I can't submit for Data Complete.
I thought that onClick="...." and defining a way to set value="true" would be a way forward, but haven't found any example while searching, and being quite the beginner, I haven't learned it all yet.
the checkbox (to be renumbered up to id 050):
<label for="completed_001">Task Completed<em class="labelrequired">*</em></label>
<input type="checkbox" id="completed_001" name="completed_001" alt="Task Completed 001" title="Task Completed 001" value="" class="validate['required']">
the function: (where the last row concerns the checkbox)
function isEmptyAction(nr) {
var pad = "000";
var nr = (pad+nr).slice(-pad.length);
return document.getElementById('taskdescription' + nr).value == '' &&
document.getElementById('TaskOwner' + nr).value == '' &&
document.getElementById('taskduedate' + nr + '_date').value == '' &&
document.getElementById('documentid' + nr).value == '' &&
document.getElementById('resultsandcomments' + nr).value == '' &&
document.getElementById('completed_' + nr).value == '';
}
= = = = = UPDATE = = = =
1) thanks for the edit improvement, fellow user dmorrow!
2) Thanks for the tips and suggestions, I got it to work eventually!
I removed the value="" from the checkbox code in the html.
This allows the entered checkmark to be recognized, when required for sumbmitting Data Complete.
I used document.getElementById('completed_' + nr).checked == false; in the function for checking that all fields are empty.
This allows removing the task block when empty.
Thanks again! You made me a happy beginner!
On this line
document.getElementById('completed_' + nr).value == '';
if you don't have a value or an empty value, it will always return true. Because instead of checked status, you are only checking it's value attribute. Instead you need to use
document.getElementById('completed_' + nr).checked;
Then it will return true/false depending on status of checkbox.
So, if you would like to check existence of checkbox field then you need
document.getElementById('completed_' + nr)
if you need the value of the checkbox either checked or not checked
document.getElementById('completed_' + nr).value
if you need the value if checkbox is checked
( document.getElementById('completed_' + nr).checked && document.getElementById('completed_' + nr).value!=='' )
Be aware of the parentheses. This will return only true if both cases are true.

Uncaught TypeError: Cannot set property 'display' of undefined

I am in the process of migrating an existing platform to a new server. I am taking the opportunity to upgrade PHP ect and standardise/debug the code as the previous maintainers have had different standards.
I have opted for PHP version 5.4.33 for now, once I have managed to move everything over to mysqli I will look to go to a more recent version. I didnt think anything server side would make a difference to AJAX/JS? As far as I am aware is it not client side?
Since I have moved the code over I am having issues with AJAX/JS. I am not the greatest at AJAX/JS and could use some assistance please. Even though every submit works differently through the entire platform I do not want to remove the AJAX/JS that already exists. I will most likely use it as an opportunity to how to use it as it makes end user experience smoother.
Using Chrome to debug I am receiving the following error on clicking the Save button:
Uncaught TypeError: Cannot set property 'display' of undefined
email_user
onclick
This is the Save button code
<span id="loading" style="color: red; font-size: x-small; display: none; text-decoration: blink;">Loading... Please wait..</span><input type="button" value="Save" class="save" onclick="if(validate()){ email_user(); }" />
This is the function code for validate()
function validate() {
var errorString = "";
if(isBlank(document.getElementById("forename").value)) {
errorString += " - Please input a forename\n";
}
if(isBlank(document.getElementById("surname").value)) {
errorString += " - Please input a surname\n";
}
if(isBlank(document.getElementById("company_name").value)) {
errorString += " - Please select a company\n";
}
if(document.getElementById("username").value != "" || document.getElementById("password").value != "") {
if(isBlank(document.getElementById("username").value)) {
errorString += " - Please input a username\n";
}
if(isBlank(document.getElementById("password").value)) {
errorString += " - Please select a password\n";
}
}
//if not a solicitor then cases mandatory
if(document.getElementById("company_role_type_id").value == 2) {
if(document.getElementById("other_view_if").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(document.getElementById("company_role_type_id").value == 3) {
if(document.getElementById("other_view_ea").value == "") {
errorString += " - Please select who can view your cases\n";
}
}
if(errorString) {
alert('Please correct the following items:-\n\n'+ errorString);
return false;
}
else {
return true;
}
}
This is the function code for email_user()
function email_user(){
if(skip_email == true){ $('user').submit(); }
var url = 'email_user.php';
var params = '?' + $('user').serialize() + '&from_edit=1';
$('loading').style.display = 'inline';
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: params,
onComplete: show_response
});
function show_response(this_request){
//alert(this_request.responseText);
var reply = this_request.responseText.evalJSON(true);
if(reply['status'] == false){ var blah = ''; }
else{ alert(reply['message']); }
//$('loading').style.display = 'none';
$('user').submit();
}
}
Thinking about it, maybe it is more to do with the Apache version?? Just in case Apache version is 2.2.15.
Any assistance you guys can give me will be greatly appreciated! If you need any more information please let me know.
Kind Regards,
n00bstacker
As previously stated in comments, your code has some issues, your line (the one that is triggering the error, can be optimized in the following way:
$('#loading').css("display","inline"); //Selector is ok now...
In the other hand, I also noticed that you have a second selector $('user') that won´t work. Remember that anything without a dot, or a sharp will be considered as an element selector (loading, and user elements, won´t exist in your document unless you created it.
Remember:
$("#myId") //id selector
$(".myClass") //class selector
If "user" is the form name, the code may work. Remember that you want to catch the form submit event.
Regards,
Guillermo
Try changing $('loading') to $('#loading')?

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

make a simple login page

hey all..
i want to make a simple login page. I have prepared two textfield.
<input type="text" id="user">
<input type="password" id="password">
<input type="button" id="go">
i want after click #go script can check:
if #user value != "admin"
then #password value != "qaubuntu"
will show and JS alert.
but if data same, will show some hidden .
can you show me how to do that?
$(function() {
$('#go').click(function() {
if($('#user').val() !== "admin" || $('#password').val() !== "qaubuntu") {
alert('Invalid login');
return false;
} else {
return true;
}
});
});
that's the quick fix (assuming you're just playing around). But you should never do it like this for a few reasons:
Anyone with half a brain can look at your JavaScript and see what the id/pw is
I always think it's better to do the user authentication at the server side
Probably a million others, it's so insecure it hurts
but for the purpose of this answer I'm assuming you're just practising with jQ.
this is in jquery, when clicking on button #go check the login data
$('#go').bind('click',function()
{
if($('#user').val() == 'admin' && $('#password').val() == 'qaubuntu'))
//ok do what you need
else
alert('username or password not valid');
});

Categories

Resources