How to update text inside Div? - javascript

Iam trying to update Div text based on js variable null or not.
This is the code used for checking var userName is null or not.
If its null i dont want to do anything.But if userName is not null then i need to append ',' to existing text inside div .
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
});
my html of the div
<div id="title" class="box">
<b>Welcome</b>
</div>
For example if userName is not null then i want div text as "Welcome ,"
if userName is null then i want div text as "Welcome"

Since you're using jQuery already...
$(document).ready(function (){
var userName = ""; // this will never get into the following if statement, always else
if (userName == undefined || userName == null) { // use if (!userName) as shorthand.
alert('empty');
} else {
alert('not empty');
var div = $('#title > b');
div.text(div.text() + ',');
}
});

You're using an odd mix of POJS and jQuery here. Here's a purely jQuery solution:
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
$('#title b').append(',');
}
});
It's a little odd that you're declaring userName as an empty string within your function - the first if condition will never execute.

A more jQuery answer, if you are interested:
var userName = "";
//var userName = "User"; // for testing
//var userName; // for testing
//var userName = null; // for testing
$(document).ready(function (){
var greeting = !!userName ? "Welcome, "+ userName + "!" : "Welcome";
$("#title b").html(greeting);
})
jsFiddle

Related

Send data to php file with javascript on submit

so basically, when someone clicks the submit input, I want to retrieve values from various inputs and spans using javascript, then send it to php using $post to then send it by email. I have already tried to delete all the javascript code (except the preventdefault and the click function) and replacing it by a alert, and when I click submit, the alert does execute as it should. But now i'm trying to figure out how to make retrieve all this data and send it by email.
I have a live example here, if you want to see what i'm trying to do.
Thanks
<script type="text/javascript">
$("#submit").click(function (e) {
e.preventDefault();
var PrimaryParentName;
var SecondaryParentName;
var PrimaryEmail;
var SecondaryEmail;
var PrimaryPhone;
var SecondaryPhone;
var Address;
var ChildName;
var ChildBirth;
var ChildAllergies;
var ChildSchool;
var ChildLevel;
var UniformSize;
var PreferedPositions;
PrimaryParentName = document.getElementById("first_parent_name")
.value;
if (document.getElementById("second_parent_name").value ==
null || document.getElementById("second_parent_name")
.value == "") {
SecondaryParentName = 'N/A';
} else {
SecondaryParentName = document.getElementById(
"second_parent_name").value;
}
SecondaryEmail = document.getElementById("first_email")
.value;
if (document.getElementById("second_email").value ==
null || document.getElementById("second_email")
.value == "") {
SecondaryEmail = 'N/A';
} else {
SecondaryEmail = document.getElementById(
"second_email").value;
}
PrimaryPhone = document.getElementById("first_phone")
.value;
if (document.getElementById("second_phone").value ==
null || document.getElementById("second_phone")
.value == "") {
SecondaryPhone = 'N/A';
} else {
SecondaryPhone = document.getElementById(
"second_phone").value;
}
Address = document.getElementById("address")
.value;
ChildName = document.getElementById("child_name")
.value;
ChildBirth = document.getElementById("child_date")
.value;
ChildAllergies = document.getElementById("child_allergies")
.value;
ChildSchool = document.getElementById("school")
.value;
ChildLevel = document.getElementById("uniform_size")
.value;
UniformSize = document.getElementById("leveldescription")
.innerHTML;
PreferedPositions = document.getElementById("Goalie")
.value;
alert(PreferedPositions + UniformSize + ChildLevel);
$.post('registration.php', {
PostPrimaryParentName: PrimaryParentName,
PostSecondaryParentName: SecondaryParentName,
PostPrimaryEmail: PrimaryEmail,
PostSecondaryEmail: SecondaryEmail,
PostPrimaryPhone: PrimaryPhone,
PostSecondaryPhone: SecondaryPhone,
PostAddress: Address,
PostChildName: ChildName,
PostChildBirth: ChildBirth,
PostChildAllergies: ChildAllergies,
PostChildSchool: ChildSchool,
PostChildLevel: ChildLevel,
PostUniformSize: UniformSize,
PostPreferedPositions: PreferedPositions
}, function () {});
});
</script>
<?php
$PrimaryParentName=$_POST['PostPrimaryParentName'];
$SecondaryParentName=$_POST['PostSecondaryParentName'];
$PrimaryEmail=$_POST['PostPrimaryEmail'];
$SecondaryEmail=$_POST['PostSecondaryEmail'];
$PrimaryPhone=$_POST['PostPrimaryPhone'];
$SecondaryPhone=$_POST['PostSecondaryPhone'];
$Address=$_POST['PostAddress'];
$ChildName=$_POST['PostChildName'];
$ChildBirth=$_POST['PostChildBirth'];
$ChildAllergies=$_POST['PostChildAllergies'];
$ChildSchool=$_POST['PostChildSchool'];
$ChildLevel=$_POST['PostChildLevel'];
$UniformSize=$_POST['PostUniformSize'];
$PreferedPositions=$_POST['PostPreferedPositions'];
$to='email#gmail.com';
$subject= 'Nouvelle inscription pour le CSEO';
$message="<span style='font-size: 26px'><b>Contact information</b></span>"."Primary parent's name: ".$PrimaryParentName."\n"."Primary parent's email: ".$PrimaryEmail."\n"."Primary parent's phone number: ".$PrimaryPhone."\n\n"."Secondary parent's name: ".$SecondaryParentName."\n"."Secondary parent's email: ".$SecondaryEmail."\n"."Secondary parent's phone number: ".$SecondaryPhone."\n\n"."Address: ".$Address."\n <hr> \n"."<span style='font-size: 26px'><b>Child's information</b></span>"."\n"."Child name: ".$ChildName."\n"."Child's date of birth: ".$ChildBirth."\n"."Allergies: ".$ChildAllergies."\n"."Child's school: ".$ChildSchool."\n"."Child's level of experience: ".$ChildLevel."\n"."Prefered positions: ".$PreferedPositions."\n"."Uniform size: ".$UniformSize;
mail($to, $subject, $message);
?>
Alright I solved it, the problem was with the if in before the $post.
if (document.getElementById("second_phone").value ==
null || document.getElementById("second_phone")
.value == "") {
SecondaryPhone = 'N/A';
} else {
SecondaryPhone = document.getElementById(
"second_phone").value;
}
I don't know what the exact issue was but it works without it and i'm fine without them.

interactive PDF Form-Validation Javascript

I'm trying to validate my interactive PDF. So if i click on a button (for validating) there's following code behind it:
var isBlank = false;
var blank = "Please fill following fields:";
var isNotValid = false;
var notValid = "Please check input data in following fields:";
var message = "";
var t = ['Division', 'Oragnisationseinheit', 'Name', 'KZZ', 'Privataddresse'];
var i;
for(var i=0; i<t.length;i++){
//validation text fields needs to be filled in
if (this.getField(t[i]).value == "") {
blank = blank + "\n" + this.getField(t[i]).name;
isBlank = true;
}
//validation text field must contain only lower case letters
if (/^[a-z]*$/.test(this.getField(t[i]).value) == false) {
notValid = notValid + "\n" + this.getField(t[i]).name;
isNotValid = true;
}
//generate message
if (isBlank == true) {
message = blank + "\n" + "\n";
}
if (isNotValid == true) {
message = message + notValid;
}
}
//check all conditions
if ((isBlank == true) || (isNotValid == true)) {
//show message
app.alert({ cMsg: message, cTitle: "Input data error" });
}
The problem is now, if I press the button there's no reaction. --> the var message wont being displayed. Where is the issue?
Thanks for all ideas.
You might try instead to add a custom validation script that would first check to be sure the field isn't blank and if not, simply change the input to lower case so the user doesn't need to modify the field themselves.
Add the following code to the custom field validate script. This should work for any text field.
if (event.value.length == 0) {
app.alert({ cMsg: event.target.name + " cannot be blank.", cTitle: "Input data error" });
}
else {
event.value = event.value.toLowerCase();
}

Basic Form Validation with JavaScript/HTML

I'm writing a form validation script for my Contact Us form I made. The script is pretty straight forward, I am wondering why it isn't working correctly.
No matter what fields I have content in, it always says that field is empty after running the script.
Here is my code:
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/
Thank you.
First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form).
Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties.
Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again.
Add .value to the elements you are trying to get and move the following code so it is inside the function.
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
You are also only checking for errors when the form is submitted using the submit button. You should do this when the form is submitted instead.
Move the onclick attribute contents to an onsubmit attribute on the form element. Better yet, bind your event listener with JS.
You aren't preventing the normal action of the form when there are errors. Presumably you want it to stop the data from submitting. Either:
Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or
Add return to the front of your onsubmit attribute value and return false from the function when there are errors.
Also note that
Your label elements are useless; they need for attributes.
You shouldn't use tables to layout (most) forms.
The values will always be strings so there is no point in comparing to null.
You are querying the dom elements but not their values. The correct way would be
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName.value==="" || firstName.value=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName.value==="" || lastName.value=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email.value==="" || email.value=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message.value==="" || message.value=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer
The issue is that you are not returning the .value of the form fields.
eg: var firstName = document.getElementById("fname").value;
Also, you should declare your vars inside the function.
Try this:
function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}

Check for Valid Email with jQuery

I am trying to use jQuery to see if a user has entered a valid email address into my text box.
Basically, I want the submit button to remain disabled by default, but on each keyup I want to see if the email address is valid, then I want to enable the button. If the user enters a valid email but then deletes parts so that it becomes invalid again (i.e. the # symbol) I want the submit button to become disabled again.
I have a partially working script here. My check or the # symbol works well, but I am having a hard time checking for .com, .co, .net, .org, .edu etc... For some reason, the button keeps enabling even though I have not entered a valid "ending" to the email.
For example "emailco#" is recognized as a valid email. Here is my script:
<script>
$(document).ready(function() {
$('#email').bind('keyup', function(e) {
var email = document.getElementById("email");
if (email.value.search("#") != -1) {
if (
(email.value.search(".com") != -1)||
(email.value.search(".co") != -1)||
(email.value.search(".org") != -1)||
(email.value.search(".net") != -1)||
(email.value.search(".gov") != -1)||
(email.value.search(".biz") != -1)||
(email.value.search(".me") != -1)||
(email.value.search(".edu") != -1)) {
document.getElementById("email_go").disabled = false;
}
else {
document.getElementById("email_go").disabled = true;
}
}
else {
document.getElementById("email_go").disabled = true;
}
});
});
</script>
Just use regex:
if (email.value.search("#") != -1) {
if (/(.+)#(.+)\.(com|edu|org|etc)$/.test(email.value))
}
var email = $('#email').val();
var pattern = ".+\\##.+\\..+";
var valid = email.match(pattern);
if (valid == null) {
alert("Not Valid");
return;
}
else{
alert("Valid");
return;
}
Try this. Of course, this is just a basic example and I'm sure that email addresses nowadays can end in more than just what's specified in the array below. But, still... you get the idea...
// Split the email to see if there's an "#" character
var split = email.split('#');
var split_count = split.length;
// If there is, then split the second string by a "."
if (split_count == 2) {
var domain = split[1].split('.');
var domain_count = domain.length;
if (domain_count == 2) {
// Store all of the accepted values for email endings
var endings = ['org', 'com', 'net', 'edu', 'info', 'biz', 'me'];
var result = $.inArray(domain[1], endings);
// If the final 3 chars of the string are in the array, then proceed
if (result > 0) {
}
}
}
I use this Regex Code to test email format using jQuery:
var email = $('.email').val();
if(email.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/))
{
alert('OK');
}

replace span text (error) after retyping vars jquery javascript

Whats the best approach for jquery realtime validation checking?
Onsubmit the span with each label gets changed to for example:
enter your email | submit | email is not correct
but when you change the value again you have to submit again to remove the email is not correct message.
So im searching for a "realtime" error handling or something. What is the best approach to do this considering my code?
<script type="text/javascript">
$(document).ready(function()
{
$('form #status').hide();
$('#submit').click(function(e) {
e.preventDefault();
var valid = '';
var required = 'is required';
var name = $('form #name').val();
var subject = $('form #subject').val();
var email = $('form #email').val();
var message = $('form #message').val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//error checking
if (name == '' || name.length <= 2)
{
valid = '<p>your name' + required + '</p>';
$('form #nameInfo').text('Name can not contain 2 characters or less!');
}
if(!filter.test(email)){
valid += '<p>Your email'+ required +'</p>';
$('form #emailInfo').text('Email addres is not valid');
}
if (message == '' || message.length <= 5)
{
valid += '<p>A message' + required +'</p>';
$('form #messageInfo').text('Message must be over 20 chars');
}
if (valid != '')
{
$('form #status').removeClass().addClass('error')
.html('<strong>Please correct errors belown </strong>' + valid).fadeIn('fast')
}
else
{
$('form #status').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
</script>
I'm not 100% sure I understand the question. Do you want to reset #emailInfo text when user corrects the input? If so, you can use either onchange, onkeypres or on focus events:
$("#email").change(function(){
$("#nameInfo").text("Enter your email");
});
Better yet, you can do your validation on corresponding field change rather than on form submit.
The following example will validate email field on each key pressed:
$("#email").keypress(function(){
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email = $('#email').val();
if(!filter.test(email)){
$('#emailInfo').text('Email addres is not valid');
} else {
$('#emailInfo').text('');
}
});
You can validate other fields in a similar way. Or you can use jQuery Validation plugin.

Categories

Resources