Some issues with JavaScript - javascript

I'm passing through some issues while trying to make this code work.
The JavaScript part :
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
function post() {
if (name === "") {
alert("You are missing something :)");
document.getElementById("name").focus();
}
else if (msg === "") {
alert("You are missing something :)");
document.getElementById("msg").focus();
}
else {
document.getElementById("content").innerHTML += ("<p id='post'>Name :. " + name + "</p><br><p id='post'>Comment :. " + msg + "</p><br><p>" + date + "</p>");
alert("Successfully posted :)");
}
}
And the body part :
<div id="content">
<h1>:. Welcome to the discussion .:</h1>
<br><br>
<p>The topic is : The structure of this website.</p>
<br>
Name/Nickname :.<br><input type="text" value="" id="name" maxlenght="32">
<br>
<p>
Message :.<br><textarea id="msg" cols="40" rows="5"></textarea>
<p>
<input type="button" value="Post" onClick="javascript:post()">
</div>
I get some issues when I press the 'post' button, it shows up the alert even being with or without letters on the 'name' and 'msg' inputs. And I can't see if the 'else' part will work because I can't even pass through the first part :c . I tried everything, but no success, hope someone can give me a light.

This section only gets run once:
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
If you want to recheck the name value when post is called, you should have name be reassigned to document.getElementById("name").value within the post function.

Related

How to use RegExp in Javascript

I want to use RegExp in else if(){} statements. How is it done?
I want to do:
If the user's value (prompt) is equal to "javascript" or "JaVaScRipT" then let the else if statement work.
<body>
<button onclick="javascript:notfic();">Click</button>
<p id="result"></p>
<script>
"use strict"
function notfic(){
let message="", result, del;
result = document.querySelector('#result');
del = prompt("Please, enter your answer");
if (del == null || del==""){
message = "You must write answer";
}else if(del == /javascript/i){
message = "You enter correct answer. Your answer is: <br> " + del;
}else{
message = "Sorry, your answer is wrong. Your answer is: <br>" + del;
}
result.innerHTML = message;
}
</script>
</body>
Your you need to call the test method:
else if(/javascript/i.test(del))
Read this for more info

How to store user input as a variable?

I am trying to design a simple companion interface for a board game I am creating. How do you request user input, and then update a variable with the new input and display the new result? ie. "What number did you roll?" -> "You are now on [this] space."
Sorry, I am very new to coding... Here is the closest I've got
<var space = 1>
<button onclick="mySpaceNumber()">Die Roll</button>
<p id="demo"></p>
<script>
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll != null) {
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
function mySpace(){
'space'= 'space'+ 'dieroll'
space
}
}
}
</script>
if (dieroll != null) { - This will always be NOT null if something isn't entered. Reason being is that it is UNDEFINED, rather than NULL. These are two different things. Null is an actual value. When a variable has been declared, but no value has been given to it then it becomes undefined.
With that said, I would make this line if (dieroll !== "undefined)"
Regarding 'space'= 'space'+ 'dieroll'
I would not put any apostraphe's in the variable's NAME, that is something you want to do when you declare a string.
Regarding this: You will want to put your code on one line.
From:
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
To:
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
The variable space is undefined, you have not initialized it or given it a value. To do that we need to add this in var space=0;
Lastly, I don't see your HTML so I'm not sure what element the variable space is supposed to reference. If it's some other box or something you can remove the var space=0; and get the value by selecting the element you need it from. Without knowing what that would be or what your html looks like I can't speculate further.
With all that said, here is where we are.
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
function mySpace(){
var space=0;
space = space + dieroll;
return space
}
}
}
Then onto the HTML
This is not valid.
Code Snippet
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("roll").value = dieroll;
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
}
function mySpace(){
result = getSpace();
return result;
}
function getSpace(){
gs1 = +document.getElementById('quantity').value + +document.getElementById('roll').value
return gs1;
}
document.getElementById('quantity').value = +document.getElementById('quantity').value + +document.getElementById('roll').value
}
function resetSpace(){
document.getElementById('quantity').value = '1';
}
<div>Roll:
<input type="number" id="roll" name="roll" style="width: 50px;" />
Current Space:
<input type="number" id="quantity" name="quantity" value="1" style="width: 50px;" />
</div>
<button onclick="mySpaceNumber()">Die Roll</button>
<button id="reset" onclick="resetSpace()">reset</button>
<div id="demo"></div>

Enable button only if text is filled in (NO SPACES)

I've looked around for an answer to my question, but all the solutions I have found do not take into account that spaces also work as input.
I have a join function, and the button shouldn't be enabled if a user only enters space. It should need actual text. Anyone has a solution to this?
Here's my function:
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#UsersOnline").show();
$("#msg").show();
$("#messaging").show();
$("#msg").focus();
ready = true;
}
you could use jquery trim()
var name = $.trim($("#name").val());
https://api.jquery.com/jQuery.trim/
EDIT:
As #David Thomas pointed out, we can also use String.prototype.trim()
var name = $("#name").val().trim();
function updateResult() {
var before = $("#name").val().replace(/\s/g,'SPACE');
var name = $("#name").val().trim();
$('#result').text('Before:' + before + "\nAfter:" + name);
}
$(document).ready(function(){
updateResult();
$('body').on('keyup','#name',function(){
updateResult();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>By default value i left left a space for the name</p>
Name : <input type="text" id="name" value=" "><br>
<br>
Value of name : <pre id="result">empty</pre>

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Unable To Send Emails With JavaScript

An old thread on Stack Overflow discusses how to use JavaScript to fill in a mailto email:
Sending emails with Javascript
I was interested in applying the technique, but couldn't get it to work.
In the code below, when I set a breakpoint on return false in the makecontact() method, and look at the URL that it logs, it looks fine.
But the browser does not open the email client.
If I hardcode the same URL in an href in the Submit button, then it launches the email client.
Why doesn't setting the href work?
ANSWER: It was the wrong href.
Fixed version:
<!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. -->
<form name="contact">
<br/>Reason for contact:
<br/>
<input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/>Product Inquiry/Presales Question<br/>
<input type="radio" name="reason" value="Support/Warranty"/>Support/Warranty<br/>
<input type="radio" name="reason" value="Feedback"/>Feedback<br/>
<input type="radio" name="reason" value="Other"/>Other<br/>
<input type="text" name="name" id="name"/>Your name:</div>
<textarea name="contacttext" rows="20" cols="60" id="contacttext"></textarea>
<button id="submit">Submit</button>
</form>
<script type="text/javascript" id="contactjs">
<!--
var submit = document.getElementById("submit");
function getreason() {
var radios, i, radio;
radios = document.getElementsByName("reason");
for (i = 0; i < radios.length; i += 1) {
radio = radios[i];
if (radio.checked) {
break;
}
}
return encodeURIComponent(radio.value);
}
function makecontact(e) {
var subject, name, text;
subject = getreason();
name = document.getElementById("name").value;
text = document.getElementById("contacttext").value;
body = "From: '" + name + "', Content: '" + text + "'";
body = encodeURIComponent(body);
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
console.log(document.location.href);
e.preventDefault();
return false;
}
if (submit.addEventListener) {
submit.addEventListener("click", makecontact, true);
} else if (form.attachEvent) {
submit.attachEvent("onclick", makecontact);
} else {
submit.click = makecontact;
}
//-->
</script>
</div>
body = "From: '
" + name + "
', Content: '
" + text + "
'";
This is not valid JavaScript. It will cause an "Unterminated string constant" error. Try this instead:
body = "From: '\n" + name + "\n', Content: '\n" + text + "\n'";
You have two main problems:
button elements don’t have hrefs (HTML4, HTML5). Setting one won’t do anything. At the end of your submit handler, you should instead set document.location.href:
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
You can’t have literal newlines in strings in JavaScript. Use \n instead:
body = "From: ' \n" + name + " \n', Content: ' \n" + text + " \n'";
Also be aware…
You should accept an event object in your event handler, and call event.preventDefault() instead of just returning false from your event handler, to stop the form from being submitted.
There’s no function called resume, but you’re using it if neither addEventListener nor attachEvent exists.

Categories

Resources