I'm having a question about javascript where I have two conditions to check if the input fields exists. But it only shows me that "opleiding exists" and not that "opleiding exists" and "domein exists".
please tell me what's wrong with my code.
Thanks very much !
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
if(document.getElementById("opleiding")){
document.write("opleiding exists");
}
if (document.getElementById("domein")){
document.write("domein exists");
}
}
</script>
</head>
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
</html>
document.write will override the existing content in the page. That's the reason why you're seeing only on message.
You must use document.body.appendChild instead to show both error messages.
function submit()
{
var opleiding = document.getElementById("opleiding");
var domein = document.getElementById("domein");
var textElement;
if(document.getElementById("opleiding")){
textElement = document.createElement("p");
textElement.textContent = "opleiding exists";
document.querySelector("#results").appendChild(textElement);
}
if (document.getElementById("domein")){
textElement = document.createElement("p");
textElement.textContent = "domein exists";
document.querySelector("#results").appendChild(textElement);
}
}
<body>
<input type="hidden" id="domein" value="domein" />
<input type="hidden" id="opleiding" value="opleiding" />
<div id="results"></div>
<div id="button" onclick="submit()">
<strong>button text</strong>
</div>
</body>
You should avoid using document.write, since that it's a deprecated method. When you use it the first time, it will write down what you want, but remove all the content of the page, as per its definition.
To do what you want you should "write" using either document.body.appendChild to append some element (like a <div>) containing text, or add some text to the document.body.innerHTML, here's an example:
function submit() {
var opleiding_div = document.createElement('div'),
domein_div = document.createElement('div');
opleiding_div.textContent = "opleiding exists";
domein_div.textContent = "domein exists";
if(document.getElementById("opleiding")){
document.body.appendChild(opleiding_div);
}
if (document.getElementById("domein")){
document.body.appendChild(domein_div);
}
}
Related
I have an html page that access an external javascript file to validate the users input. My button doesnt seem to be doing anything and I dont understand why.
<html lang = "en">
<head>
<title>random</title>
</head>
<body>
<form>
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="15">
<input type="button" value="validate" onclick="validationFunction()">
<p id = "validationResults"></p>
</body>
</html>
//My external JS file that is supposed to validate the pattern WEB.110#4101_sp-2017
function validationFunction(input) {
var myRegularExpression = /([a-z]{3})(\W\d{3})(\W\d{4})(\W[a-z]{2})(\W\d{4})/gi;
return (myRegularExpression.test(input));
}
if (validationFunction(userInput)){
text = "valid";
} else {
text = "invalid";
}
document.getElementById("validationResults").innerHTML = text;
The below code works for what you want to achieve. Issues I noticed with your code:
Your form element had no closing tag
Rather than adding an onclick to a button within a form, you are better submitting the whole form, and grabbing the event object from an onsubmit event
You need to preventDefault on the event which stops the page refreshing
Your maxLength was set to 15 but your target expression is 20 characters
Your RegEx works, but could be cleaner
<!DOCTYPE html>
<html>
<head>
<title>random</title>
<script src="./script.js" defer></script>
</head>
<body>
<form id="form">
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="20"/>
<input type="submit"></input>
</form>
<p id="validationResults"></p>
</body>
</html>
const form = document.getElementById("form");
const paragraph = document.getElementById("validationResults");
form.addEventListener('submit', validationFunction);
function validationFunction(event) {
event.preventDefault();
const userInput = event.target.querySelector("#userInput").value;
const regEx = /([a-z]{3}(.\d{3})(#\d{4})(_[a-z]{2})(-\d{4}))/gi;
const isValid = regEx.test(userInput);
if (isValid) {
paragraph.innerHTML = "Valid";
} else {
paragraph.innerHTML = "Invalid";
}
};
So i'm trying to make a simple comments page but I can't seem to get it working :/ Is there something wrong with the code? I'm trying to use only javascript since I have not learned JQuery
function action(){
var input = document.getElementById('header').value;
localStorage.setItem('comment',input);
document.getElementById('header').value=" ";
var getInput = localStorage.getItem('comment');
var date = Date();
var parag = document.createElement('P')
parag.innerText=getInput;
document.getElementById('hello').appendChild=parag;
}
<textarea id='header' type='text' rows='6' cols='100' name='server'>
</textarea>
<input onclick="action();" type="button" value='Comment'>
<span id='hello'></span>
document.getElementById('hello').appendChild=parag;
You are not calling the appendChild function properly. You are assigning instead. You should do
document.getElementById('hello').appendChild(parag);
Note: in below codes I removed the local storage because of security issues.
--
function action(){
var input = document.getElementById('header').value;
//localStorage.setItem('comment',input);
document.getElementById('header').value=" ";
// var getInput = localStorage.getItem('comment');
var date = Date();
var parag = document.createElement('P')
parag.innerText="getInput";
document.getElementById('hello').appendChild(parag);
}
<textarea id='header' type='text' rows='6' cols='100' name='server'>
</textarea>
<input onclick="action();" type="button" value='Comment'>
<span id='hello'></span>
Just change you append child to :
document.getElementById('hello').appendChild(parag);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<script type="text/javascript" charset="utf-8">
function action(){
var input = document.getElementById('header').value;
localStorage.setItem('comment',input);
document.getElementById('header').value=" ";
var getInput = localStorage.getItem('comment');
var parag = document.createElement('P')
parag.innerText=getInput;
document.getElementById('hello').appendChild(parag);
}
</script>
<body>
<textarea id='header' type='text' rows='6' cols='100' name='server'>
</textarea>
<input onclick="action();" type="button" value='Comment'>
<div id='hello'></div>
</body>
</html>
The syntax for Node.appendChild is wrong.
You can see how to use it in the DOM Living Standard.
The appendChild(node) method, when invoked, must return the result of appending node to context object.
You should also consider keeping a reference to header instead of querying the DOM twice.
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
<script>
function billingFunction()
{
var shippingName = document.getElementById("shippingName");
if(document.getElementById("same").checked )
{
document.getElementById("billingName").value= shippingName.value;
}
else
{
document.getElementById("billingName").removeAttribute("required");
}
}
</script>
</head>
<body>
<form>
<fieldset>
<legend>Shipping Information</legend>
<label for ="shippingName">Name:</label>
<input type = "text" name = "Name" id = "shippingName" required><br/>
</fieldset>
<input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>
<label for = "same">Is the Billing Information the Same?</label>
<fieldset>
<legend>Billing Information</legend>
<label for ="billingName">Name:</label>
<input type = "text" name = "Name" id = "billingName" required><br/>
</fieldset>
<input type = "submit" value = "Verify"/>
</form>
</body>
</html>
Whenever the checkbox is checked, the code should automatically copy the values from first field into the second field. If the checkbox is unchecked, the second one should go blank. as per my code the first requirement is ok, but I couldn't make it blank when it is unchecked. Can anyone help plz.
Add document.getElementById("billingName").value = null; to the else clause.
Fiddle
Just set the value to an empty string in the else clause
function billingFunction() {
var shippingName = document.getElementById("shippingName");
var billingName = document.getElementById("billingName");
if(document.getElementById("same").checked ) {
billingName.value = shippingName.value;
} else {
billingName.removeAttribute("required");
billingName.value = "";
}
}
You only need to modify the else block
else{
document.getElementById("billingName").value="";
}
JSFIDDLE
EDIT
You have put the billing function inside header. You must be comming across reference error.
You can put this billing function inside window.onload or pu this script near closing body tag
window.onload= function(){
billingFunction;
}
function billingFunction(){ //Rest of code}
JSFIDDLE with window.onload
I want to use the input of the user from the prompt window.
This is my JavaScript form:
var answer;
function load()
{
answer=prompt("what is your name?", "Write your name here");
return answer;
}
function hideNsee() {
var HNS = document.getElementById("invite");
if(HNS.style.display == "none")
HNS.style.display = "block";
else HNS.style.display = "none";
}
and I want to use the input, in this case his or her name in my HTML invitation signature.
This is the invitation format, and the input will be in this case "shai".
for the second part, the user invites someone "Moshe Cohen" and this also is sent to the invitation.
How can I use the input and send it to the invitation?
When I try to save it to the "answer" VAR it does nothing.
I'm clearly missing something I need to do.
When I know how to take it from the prompt window I will cast this on the other inputs too, the invite, time, and place.
I hope it will be the same method.
this is the HTML part of my program, if its needed
<html>
<head>
<link rel="stylesheet" href="CSS.css"/>
<script src="JavaScript.js">
</script>
</head>
<body onload= "load();">
<span id="imvite">Invite:</span>
<input
onmouseover="this.value=this.getAttribute('data-value');"
data-value="Who is it?"
onmouseout="this.value='';"
/> <br></br>
<span id="time">Time:</span>
<input
onmouseover="this.value=this.getAttribute('data-value');"
data-value="At what time?"
onmouseout="this.value='';"
/> <br></br>
<span id="place">Place:</span>
<input
onmouseover="this.value='where is the event?';"
onmouseout="this.value='';"
/> <br></br>
<button onclick="hideNsee();">generate invite</button>
<div id="invite" style="display:none;">
<div id="date">
10/3/2015
</div>
<h1>Invitation<h1>
</div>
</body>
</html>
I think this is what you mean:
function load() {
answer=prompt("what is your name?", "Write your name here");
var idInput = document.getElementById('nameId');
idInput.value = answer;
}
And in the HTML add the id to the element like so:
<input id="nameId"
onmouseover="this.value=this.getAttribute('data-value');"
data-value="Who is it?"
onmouseout="this.value='';"
/>
For some reason I get an document.getElementById('id') is null JS error on line 7 with the following markup and script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
document.getElementById('calculate').onclick = function calculateQuad()
{
var inputa = document.getElementById('variablea').value;
var inputb = document.getElementById('variableb').value;
var inputc = document.getElementById('variablec').value;
root = Math.pow(inputb,2) - 4 * inputa * inputc;
root1 = (-inputb + Math.sqrt(root))/2*inputa
root2 = (-inputb + Math.sqrt(root))/2*inputa
document.getElementById('root1').value = root1;
document.getElementById('root2').value = root2;
if(root<'0')
{
alert('This equation has no real solution.')
}
else {
if(root=='0')
{
document.getElementById('root1').value = root1
document.getElementById('root2').value = 'No Second Answer'
}
else {
document.getElementById('root1').value = root1
document.getElementById('root2').value = root1
}
}
};
document.getElementById('erase').onlick = this.form.reset();
</script>
<style>
#container
{
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
a:<input id="variablea" value="" type="text">
<br/>
b:<input id="variableb" value="" type="text">
<br />
c:<input id="variablec" value="" type="text">
<br />
<input id="calculate" value="Calculate!" type="button">
<input id="erase" value="Clear" type="button">
<br />
<br />
Roots:
<br />
<input id="root1" type="text" readonly>
<br />
<input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>
What's the real problem here?
It is indeed null. Your element doesn't exist on the page yet.
Either:
Move your <script> block below your code
Add a window.onload event.
Alternatively: window.onload = function(){} works as well
If you don't feel like including jQuery, then document.ready = function () {} will work fine too.
At the point which the javascript is actually run, there is no element with an id of 'calculate'. You need to make sure your javascript runs after your required elements have been created. My advice would be to use a common javascript framework like jquery. You would then just attach your script to run on dom ready:
$(document).ready(function() {
// Handler for .ready() called.
});
You can fix it by moving the script to the end of the body, or try to use window.onload, or window.addEventListenner
Check the http://v3.thewatchmakerproject.com/journal/168/javascript-the-dom-addeventlistener-and-attachevent
and http://javascript.about.com/library/blonload.htm
using windows.onload
add link file script or script below "body end tag"