Create button onclick event inside javascript - javascript

I know about the way of using html to occur an event when button is clicked
<onclick="function()">
but I was wondering If i could do this inside javascript so I created an event listener once event happens my function runs but I dont really know why it's not working.
setTimeout(() => {
alert("hi starquest");
}, 200);
var submit = document.getElementById('submit');
var input1 = document.getElementById('xname')
var input2 = document.getElementsByTagName('text')
submit.addEventListener("click", function(event) {
getUpdate();
});
function getUpdate() {
let text;
if (input1 == "nokia" && input2 == "nokia") {
text = "nuke"
} else {
text = "input nokia in both input"
}
document.getElementById("demo").innerHTML = text;
}
body {
background-image: url('https://backgroundcheckall.com/wp-content/uploads/2017/12/technology-background-image-11.jpg');
}
<h1>Input your text here</h1>
<label for="fname"></label> <input type="text" id="xname" name="fname"> + <label for="lname"></label> <input type="text" id="lname" name="lname"> =
<button>Submit</button>
<p id="demo"></p>

Few things:
You don't have anything with the id submit
You don't have a tag named text. You're looking for the element with the id lname.
setTimeout(() => {
alert("hi starquest");
}, 200);
var submit = document.getElementById('submit');
var input1 = document.getElementById('xname')
var input2 = document.getElementById('lname');
submit.addEventListener("click", function(event) {
getUpdate();
})
function getUpdate() {
let text;
if (input1.value == "nokia" && input2.value == "nokia") {
text = "nuke"
} else {
text = "input nokia in both input"
}
document.getElementById("demo").innerHTML = text;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-image: url('https://backgroundcheckall.com/wp-content/uploads/2017/12/technology-background-image-11.jpg');
}
</style>
<script src="test.js"></script>
</head>
<body>
<h1>Input your text here</h1>
<label for="fname"></label> <input type="text" id="xname" name="fname"> + <label for="lname"></label> <input type="text" id="lname" name="lname"> =
<button id="submit">Submit</button>
<p id="demo"></p>
</body>
</html>

There are a few issues with your code.
input2 is empty, because there is no element with tagname `text"
submit variable is undefined, because there is no element with id submit
you are comparing input1 which is an element to a string, you want compare it's value instead (the same goes to input2 once it's properly defined)
the result of the condition is reversed when it's true it will show "nuke"
setTimeout(() => {
alert("hi starquest");
}, 200);
var submit = document.getElementById('submit');
var input1 = document.getElementById('xname')
var input2= document.getElementById('lname')
submit.addEventListener("click", function (event) {
getUpdate();
})
function getUpdate(){
let text;
if(input1.value == "nokia" && input2.value == "nokia"){
text = "input nokia in both input"
} else {
text = "nuke"
}
document.getElementById("demo").innerHTML = text;
}
<h1>Input your text here</h1>
<label for="fname"></label> <input type="text" id="xname" name="fname"> + <label for="lname"></label> <input type="text" id="lname" name="lname"> =
<button id="submit">Submit</button>
<p id="demo"></p>

Related

Trying to check for empty value in input

I have an input box that changes another paragraph in my site with JavaScript. It works flawlessly, except for the fact that when I enter nothing in the input, it blanks out the paragraph.
I don't want this to happen. I've tried almost every piece of code I've found online to fix this issue but nothing has worked.
<div class="tasklist">
<p id="task1" style="color:#d3d3a3">You don't have any tasks.</p>
</div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
element.innerHTML = (value);
document.getElementById("task1").style.color = "white";
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();" onclick="changeColor()">+ Add</button>
<div id="tasklist">
<p id="msg" style="color:red">You don't have any tasks.</p>
</div>
<br>
<script>
const element = document.getElementById("msg");
element.style.display = "none";
function add() {
let value = document.getElementById("task").value;
if (value && value.trim() != "") {
document.getElementById("task").value = "";
element.style.display = "none";
const taskContainer = document.getElementById('tasklist');
const task = document.createElement('p');
task.textContent = value;
taskContainer.append(task)
} else {
element.style.display = "block";
}
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="add();">+ Add</button>
First of all add value checker - it will prevent from setting innerHTML as "".
Secondly i think You want to add element with another task, not removing older ones.
use .append() to add at the end of parent or prepend() to add at the begginning of parrent.
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function changeColor(){console.log("color")};
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.append(
Object.assign(
document.createElement("p"),
{textContent:value}
)
);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();changeColor()" >+ Add</button>
if You rather want to replace Your first child then
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.replaceChild(Object.assign(document.createElement("p"),{textContent:value}),element.firstChild);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue()" >+ Add</button>

Inline error message still displayed after the user adds text to input fields

When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});

how can i solve the double submit problem in javascript code

what i would like are 2 input fields with a submit button.
the first field is the request for a username, the second field is a password.
if the user presses submit, the value of the fields should be below it.
but for a reason it doesn't quite work. if the user presses submit a second, then the result is written after it. and the intention is that the text of the first submit is completely replaced.
also the checker function does not work.
could anyone help?
var titles = [];
var usernameInput = document.getElementById("username");
var passwordBox = document.getElementById("password");
var messageBox = document.getElementById("display");
function CHECKER() {
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value != "") {
user.title.value = "";
alert("GEEF EEN GELDIGE WAARDE AUB");
}
}
function insert() {
titles.push(usernameInput.value);
titles.push(passwordBox.value);
clearAndShow();
}
function clearAndShow() {
usernameInput.value = "";
passwordBox.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "De opgegeven gebruiksnaam en wachtwoord zijn: " + titles.join(", ") + "<br/>";
}
<html>
<head></head>
<body>
<div class="wb-stl-custom3">
<label for="username">gebruikersnaam:</label>
</div>
<div>
<input id="username" type="text" maxlength="15" onkeyup="CHECKER()">
</div>
<div class="wb-stl-custom3" ;>
<label for="password">wachtwoord: </label>
</div>
<div>
<input id="password" type="password" maxlength="30" onkeyup="CHECKER()">
</div>
<input type="submit" value="CHECH" onclick="insert()" />
<div class="wb-stl-custom3" , id="display"></div>
</body>
</html>
I changed your CHECKER() so it will check each input field. Your code was explicitly written to add and not replace content into your titles array. If you want the values to be replaced you will need something like the following:
var titles = [];
var usernameInput = document.getElementById("username");
var passwordBox = document.getElementById("password");
var messageBox = document.getElementById("display");
function CHECKER(inp) {
if (!inp.value.match(/[a-zA-Z]$/) && inp.value != "") {
inp.value = "";
alert("GEEF EEN GELDIGE WAARDE AUB");
}
}
function insert() {
titles=[usernameInput.value,
passwordBox.value];
clearAndShow();
}
function clearAndShow() {
usernameInput.value = "";
passwordBox.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "De opgegeven gebruiksnaam en wachtwoord zijn: " + titles.join(", ") + "<br/>";
}
<html>
<head></head>
<body>
<div class="wb-stl-custom3">
<label for="username">gebruikersnaam:</label>
</div>
<div>
<input id="username" type="text" maxlength="15" onkeyup="CHECKER(this)">
</div>
<div class="wb-stl-custom3" ;>
<label for="password">wachtwoord: </label>
</div>
<div>
<input id="password" type="password" maxlength="30" onkeyup="CHECKER(this)">
</div>
<input type="submit" value="CHECH" onclick="insert()" />
<div class="wb-stl-custom3" , id="display"></div>
</body>
</html>

Javascript innerHTML is automatically overwritten and nullified [duplicate]

This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Closed 1 year ago.
I was just practising HTML DOM and Forms, and I wrote a simple code, in which we take values from the form and display them in a <p> tag :
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
<script>
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
</script>
</body>
</html>
The problem is that when I press submit, the "hi" is replaced by " David Beckham " just for a millisecond, and is again changed to "hi". So by pressing submit continuously, I can see the text being changed again and again.
I don't understand what is happening, It is working, but it is not working. I don't see any errors in the code. Maybe it's code-related, or browser-related, or machine-related.
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I don't why, but it is working in this snippet, but now in my browsers. I am using Macbook Air. I tried running it on both Safari and Chrome. Any help would be appreciated.
That is because onsubmit it will submit the form and refresh the form. So stop the default behaviour using event.preventDefault
function getFormvalue(e) {
e.preventDefault();
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML = text;
}
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue(event)">
First name: <input type="text" name="fname" value="David"><br> Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
You need to prevent form submision
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="event.preventDefault(); getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

how to show user input in the body when a button is clicked

I'm trying to display a user input on a separate div, but only have it appear when a button is clicked. I think i have it set up but I'm just not sure how to display the input. can someone help me with how it can be done?
<script>
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function(){
console.log("Call has been set");
userinput.style.display = "block";
</script>
<input id="callerIDInput" type="text" value="" >
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Set the input value to the innerHTML of the div
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function() {
console.log("Call has been set");
userinput.innerHTML = document.getElementById('callerIDInput').value
})
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Use innerHTML of the DIV to set the value.
HTML
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt' onclick="Display()">CALL</button>
Javascript
function Display()
{
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
var callerIDInput = document.getElementById("callerIDInput");
console.log("Call has been set");
userinput.style.display = "block";
userinput.innerHTML = callerIDInput.value;
}

Categories

Resources