(DOM issue) not returning anything - javascript

I'm new to JavaScript and I was trying to manipulate the value of an HTML h2 element with the class of "text" when the users clicks on the button with the id "push" and change it to the value of the input class="inputV", however i noticed that when there's no value in the input field the whole block just disappears so I tried to return a different value if the input is not true! so how do i go out about doing this! that's what I've tried so far.
function input(){
var inputValue= document.getElementById('inputV').value;
var text = document.querySelector('.text').textContent;
if (inputValue){
text = inputValue;
}else{
text = 'Null';
}
return text;
};
document.getElementById('push').addEventListener('click',input);
<div class=container><h1>JavaScript OOP</h1>
<div>
<form class="input">
<input id="inputV" type="text" name="name" placeholder="Enter your Name">
</form>
</div>
<div><h2 class="text">Results</h2></div>
<button id="push" value="Sign me in" onclick="input()">Sign me in</button>
</div>

Once you set onclick="input()" for the button you don't need to extra define an event listener. Also you can make the function body a bit shorter
function input(){
var inputValue= document.getElementById('inputV').value;
var text = document.querySelector('.text');
text.textContent = inputValue || 'Null';
};
// document.getElementById('push').addEventListener('click',input);
<div class=container><h1 class="text">JavaScript OOP</h1>
<div>
<form class="input">
<input id="inputV" type="text" name="name" placeholder="Enter your Name">
</form>
</div>
<div><h2 class="text">Results</h2></div>
<button id="push" value="Sign me in" onclick="input()">Sign me in</button>
</div>

Initialization of text is not needed, just declare it.
Replace your return text with assignment to <h2>as below
function input(){
var inputValue= document.getElementById('inputV').value;
//var text = document.querySelector('.text').textContent;
var text;
if (inputValue){
text = inputValue;
}
else{
text = 'Null';
}
// return text;
document.querySelector('.text').textContent = text;
}
document.getElementById('push').addEventListener('click',input);

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>

How to display the accessed (thru for loop) objects in array in HTML using javascript

I had a form from HTML. The input data from form will go to the multidimensional array that I made in JS. Then I will use for loop to access the objects in array in order to display the object values in the HTML div. In html, it only displays [object,object]
var data = [];
var i, item;
function myForm(event){
event.preventDefault();
var name = document.getElementById("name").value; //Getting Values from the form of HTML
var phone = document.getElementById("phone").value; //Getting Values from the form of HTML
var bday = document.getElementById("bday").value; //Getting Values from the form of HTML
var email = document.getElementById("email").value; //Getting Values from the form of HTML
var pWord = document.getElementById("pWord").value; //Getting Values from the form of HTML
var age = document.getElementById("bday").value; //Getting Values from the form of HTML
var ageValue;
var Bdate = document.getElementById("bday").value; //Getting Values from the form of HTML and calculating the age of the user
var Bday = +new Date(Bdate);
ageValue = ~~ ((Date.now() - Bday) / (31557600000));
var theBday = document.getElementById("age");
theBday.innerHTML = ageValue;
var userObject = {
name: name,
phone: phone,
bday: bday,
email: email,
pWord: pWord,
ageValue: ageValue,
}; //The values i get from my Input in html. The userObject will be in a array data[]
data.push(userObject);
for (i=0 ; i <data.length ; i++){
for (item in data[i]){
document.getElementById("demo3").innerHTML=(item + data[i][item]); //I'm trying to display the details from my form but the only thing show up is [object,object]
}
}
}
<body>
<div id="navBar">
HOME
LOG IN
SIGN UP
</div>
<center><h1>Sign Up Form</h1></center></br></br>
<div id="format">
<form id="myForm" onsubmit="myForm(event)">
<b>Name:</b></br>
<input type="text" name="name" id="name" maxlength="50" required="required" value="1234"></input></br>
<b>Phone Number:</b></br>
<input type="phone" name="phone" id="phone" maxlength="20" required="required" value="123"></input></br>
<b>Birthday:</b></br>
<input type="date" name="bday" id="bday" required="required" value="2010-05-02"></input></br>
<b>Email:</b></br>
<input type="email" name="email" id="email" maxlength="50" required="required" value="asasa#yahoo.com"></input></br>
<b>Password:</b></br>
<input type="password" name="pWord" id="pWord" maxlength="50" required="required" value="fgfghff"></input></br>
<button type="submit" name="submit" id="submit" value="Submit" onsubmit="myData()" >Submit</button>
<button type="reset" name="reset" id="reset" value="reset">Reset</button>
</form>
<div>
<p id="demo" onsubmit="myData()"></p>
</div>
<div id="result" onsubmit="myForm(event)">
<center>Result</center>
Name:<p id="name1"></p>
Phone Number:<p id="phone1"></p>
Birthday:<p id="bday1"></p>
Email:<p id="email1"></p>
Password:<p id="pWord1"></p>
Age:<p id="age"></p>
</div>
<div id="sample">
<p id="demo3" onsubmit="myForm(event)"></p>
</div>
</div>
</body>
The problem in the above code is this line
document.getElementById("demo3").innerHTML=(item + data[i][item]);
which is replacing the content of div#demo3 instead of appending so use this line instead
document.getElementById("demo").innerHTML+=(item + data[i][item]);
Here is a working example in jsfiddle.
I did not face [object,object] problem. If you can post your html code problem can be identified easily.
Update
Clear the content of div#demo before running the loop again.
document.getElementById("demo").innerHTML = "";
Check this updated jsfiddle.

getting value from input and displaying in a div

I am trying to get the value of an input and display it in a div under it, while the user is typing. and i want to do it with vanilla js. no j query.
MY HTML:
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>
MY JS:
var input = document.getElementById('inputText').value;
var showQuestion = document.getElementsByClassName('displayQuestion');
function myDisplay(e){
showQuestion.innerHTML = input;
}
Try this:
function myDisplay(e) {
var input = document.getElementById('inputText').value;
var showQuestion = document.getElementById('displayQuestion');
showQuestion.innerHTML = input;
}
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay(this.value)"/>
</div>
<div id="displayQuestion"></div>
Here you go with VannilaJS way,
Recommendation: Change the name of the function myDisplay() to something meaningful like displayQuestion()
var targetElm = document.getElementsByClassName('displayQuestion');
var inputElm = document.getElementById('inputText');
function myDisplay() {
if(targetElm && targetElm.length > 0){
targetElm[0].innerHTML = inputElm.value;
}
}
<div id="userInputBox">
<input id="inputText" type="text"
placeholder="Enter your question" size ="50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>

Form validation: remove error after onkeydown in input

I am working on my first for validation, really basic.
If you leave the 'username' input blank it will turn the username input border red and also place an alert icon in the input.
I am trying to 'remove' what was added when the validation failed as soon as the user starts typing in the input that caused the error.
So the scenario is: The user leaves Username blank, clicks Submit and then the border of the Username input goes red and an error icon appears. They then go back and they add their username into the Username input after the first character they type into the Username box I want the red border and error icon to disappear.
However my attempts have failed
My Fiddle
JS
function contactForm() {
var theForm = document.forms.contact;
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
theForm.onsubmit = function() {
if (theForm.username.value === '') {
errorUsername.style.display = 'block';
usernameInput.className = 'form__input form__input--red rounded-4';
return false;
} else {
theForm.username.onkeydown = function() {
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
};
return true;
};
};
};
contactForm();
HTML
<form name="contact" action="#" novalidate>
<div class="input__holder">
<input id="username" name="username" type="text" class="form__input rounded-4" placeholder="Username">
<div id="username-error" class="input__error">!</div>
</div>
<div class="input__holder">
<input name="password" type="password" class="form__input rounded-4" placeholder="Password">
</div>
<div class="input__holder">
<input name="email" type="text" class="form__input rounded-4" placeholder="E-mail">
</div>
<button type="submit" id="" class="submit-button rounded-4">Submit</button>
</form>
CSS
Too long, in Fiddle :)
You can add something like this on javascript
document.onkeyup = function() {
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
if (usernameInput.value.length === 0) return;
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
}
Here the fiddle:
https://jsfiddle.net/12apmo5j/12/
I think this solves your problem :)

Validating form after error has been shown

I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}

Categories

Resources