I'm new to javascript and I was making a simple program to reply
but the if statement doesn't work.
Here's my code :
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var value = document.getElementById('myInput').value;
var answer = document.getElementById('answer');
var question = "Hi";
function message() {
if ( value == question) {
answer.innerHTML = "Hi, how can i help you?";
} else {
answer.innerHTML = "Hi ...";
}
}
and here's the html part:
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>
The problem is that you're fetching the value before you have a chance to fill it in.
Instead, fetch it inside the message function.
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var answer = document.getElementById('answer');
var question = "Hi";
function message() {
var value = document.getElementById('myInput').value;
if (value == question) {
answer.innerHTML = "Hi, how can i help you?";
} else {
answer.innerHTML = "Hi ...";
}
}
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>
Place your var value = document.getElementById('myInput').value; inside the button click function
DEMO
var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var answer = document.getElementById('answer');
var question = "Hi";
function message() {
var value = document.getElementById('myInput').value;
console.log(value);
console.log(question);
if (value === question) {
answer.innerHTML = "Hi, how can i help you?";
} else {
answer.innerHTML = "Hi ...";
}
}
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>
Related
I am creating a comment box and I managed to append whatever I type to a div I wanted, however I have added another input and trying to append that along with the comments, however when I do this the second time,it appends both the previous and current comment therefore the previous comment duplicates. I know I'm doing something wrong in my display_commnents function, however I'm not entirely sure what it could be, basically I just want whatever is entered on both title and comments to append on the comment-box with title on top and comment just below. Below is my code:
<div class="container">
<h1>Write New Post</h1>
<form>
<input id="title" type="text" placeholder="Title" value="">
<textarea id="" placeholder="Leave us a comment" value=""></textarea>
<input id="giphy" type="text">
<div class="btn">
<input id="submit" type="submit" value="comment">
<button id="clear">Cancel</button>
</div>
</form>
</div>
<div class="comments">
<h2>Comments</h2>
<div id="comment-box" value="submit">
</div>
</div>
And this is my JS code:
const title = document.querySelector('#title')
const field = document.querySelector('textarea');
const textBackUp = title.getAttribute('placeholder')
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const titleText = document.getElementById('title')
const comments = document.getElementById('comment-box')
let title_arr = [];
let comments_arr = [];
title.onfocus = function(){
this.setAttribute('placeholder', '')
}
title.onblur = function(){
this.setAttribute('placeholder', textBackUp)
}
field.onfocus = function(){
this.setAttribute('placeholder','')
this.style.borderColor = '#333'
btn.style.display = 'block'
} // when clicking on this, placeholder changes into ' ', border colour changes and buttons will appear.
field.onblur = function(){
this.setAttribute('placeholder',backUp)
} //click away, placeholder returns
const display_comments = () => {
let list = '<ul>'
title_arr.forEach(title => {
comments_arr.forEach(comment => {
list += `<li>${title} <br>${comment}`
})
})
list += '</ul>'
comments.innerHTML = list
}
clear.onclick = function(e){
e.preventDefault();
btn.style.display = 'none'
title.value = ''
field.value = ''
display_comments()
}
submit.onclick = function(e){
e.preventDefault();
const head = title.value;
const content = field.value;
if(head.length > 0){
title_arr.push(head)
display_comments();
title.value = '';
}
if(content.length > 0){
comments_arr.push(content)
display_comments();
field.value = '';
}
}
any help would be appreciated
The problem is that you have a double nested loop, producing a Cartesion product of the all the introduced titles and the comments.
To solve this, use only one array for collecting the input, so that title and comment are always kept together in one array entry. Such an entry can be an object with two properties, one for the title, and one for the comment.
Here is your code adapted, just for fixing that issue:
const title = document.querySelector('#title')
const field = document.querySelector('textarea');
const textBackUp = title.getAttribute('placeholder')
const backUp = field.getAttribute('placeholder')
const btn = document.querySelector('.btn');
const clear = document.getElementById('clear')
const submit = document.querySelector('#submit')
// const comments = document.querySelector('#comment-box')
const titleText = document.getElementById('title')
const comments = document.getElementById('comment-box')
let arr = []; // Only one array
title.onfocus = function(){
this.setAttribute('placeholder', '');
}
title.onblur = function(){
this.setAttribute('placeholder', textBackUp);
}
field.onfocus = function(){
this.setAttribute('placeholder','');
this.style.borderColor = '#333';
btn.style.display = 'block';
}
field.onblur = function(){
this.setAttribute('placeholder', backUp);
}
const display_comments = () => {
let list = '<ul>';
// Only one loop -- over objects with two properties
arr.forEach(({head, content}) => {
list += `<li><b>${head}</b><br>${content}`;
})
list += '</ul>';
comments.innerHTML = list;
}
clear.onclick = function(e){
e.preventDefault();
btn.style.display = 'none';
title.value = '';
field.value = '';
display_comments();
}
submit.onclick = function(e){
e.preventDefault();
const head = title.value;
const content = field.value;
// Only one if-block
if(head.length > 0 || content.length > 0){
arr.push({head, content}); // Only one push -- of an object
display_comments();
title.value = '';
field.value = '';
}
}
<div class="container">
<h1>Write New Post</h1>
<form>
<input id="title" type="text" placeholder="Title" value="">
<textarea id="" placeholder="Leave us a comment" value=""></textarea>
<div class="btn">
<input id="submit" type="submit" value="comment">
<button id="clear">Cancel</button>
</div>
</form>
</div>
<div class="comments">
<h2>Comments</h2>
<div id="comment-box" value="submit">
</div>
</div>
Can someone explain to me or figure it out. I dont know where I made a mistake here. I have javascript and html code where I get input from user for a flight. I want to make a counter to count all flights function counter() but it gives me the value of name. And another problem is I want when I click on the Accept button to make the background of the div element green function changeColor().
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
var btn1 = document.createElement("BUTTON");
var btn2 = document.createElement("BUTTON");
var t1 = document.createTextNode("Accept");
var t2 = document.createTextNode("Reject");
btn1.appendChild(t1);
btn2.appendChild(t2);
divForOutput.innerHTML += name.value +", " + plainNum.value +"<br>" + "Radius: " + radius.value +", "+"Altitude: "+altitude.value+"<br>"+type.value+"<br>";
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
btn1.setAttribute('onclick','changeColor(this);');
btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
var parentofChild = document.getElementById("output");
output.div.background = green;
}
function counter(){;
var sum = document.getElementsByClassName("printing");
var counter = 0;
for(var i = 0;i <sum.length;i++){
counter+=parseInt(sum[i].innerHTML);
}
document.getElementById("total").innerHTML = counter;
}
<h1>Register flight</h1>
<form>
<div>
<label>Name and surname</label>
<input type="text" id="name">
</div>
<div>
<label>Number plate</label>
<input type="text" id="plainNum">
</div>
<div>
<label>Coordinates</label>
<input type="text" id="coordinates">
</div>
<div>
<label>Radius</label>
<input type="text" id="radius">
</div>
<div>
<label>Altitude</label>
<input type="text" id="altitude">
</div>
<div>
<label>Type</label>
<select id="type">
<option value="Comercial">Comercial</option>
<option value="Buissines">Buissines</option>
</select>
</div>
<div>
<input type="button" value="Submit" onclick="addRow();">
</div>
</form>
<divи>
<h3>Registered flights</h3>
<p>Total:<span id="total">0</span></p>
</div>
<div id="output">
</div>
Below I've fixed some of the code and made things a bit better.
function addRow(){
var name = document.getElementById("name");
var plainNum = document.getElementById("plainNum");
var coordinates = document.getElementById("coordinates");
var radius = document.getElementById("radius");
var altitude = document.getElementById("altitude");
var type = document.getElementById("type");
if(!name.value || !plainNum.value || !coordinates.value || !radius.value || !altitude.value || !type.value){
alert("Enter all values");
return;
}
var output = document.getElementById("output");
var divForOutput = document.createElement("DIV");
//var btn1 = document.createElement("BUTTON");
//var btn2 = document.createElement("BUTTON");
//var t1 = document.createTextNode("Accept");
//var t2 = document.createTextNode("Reject");
//btn1.appendChild(t1);
//btn2.appendChild(t2);
divForOutput.innerHTML = `
${name.value}<br>
Radius: ${radius.value}<br>
Altitude: ${altitude.value}<br>
${type.value}<br>
<button onclick="changeColor();">Accept</button>
<button onclick="disableButtons();">Reject</button>
`;
divForOutput.appendChild(btn1);
divForOutput.appendChild(btn2);
divForOutput.setAttribute('class','printing');
output.appendChild(divForOutput);
//btn1.setAttribute('onclick','changeColor(this);');
//btn2.setAttribute('onclick','disableButtons()');
// name.value = "";
// plainNum.value = "";
// coordinates.value = "";
// radius.value = "";
// altitude.value = "";
counter();
}
function disableButtons(){}
function changeColor(){
const output = document.getElementById("output");
output.style.backgroundColor = "green";
}
function counter(){;
const sum = document.getElementsByClassName("printing");
const counter = sum.getElementsByTagName('div').length;
return document.getElementById("total").innerHTML = counter;
}
There is an explanation for the background color here
As for the counter; what I did was count the div elements inside of the output div. That will give you the amount of flights a user has.
Your color setting had several problems. You don't use output.div.background to set the color, and you were using the undefined variable green instead of the string "green". This works:
function changeColor(){
var output = document.getElementById("output");
output.style.backgroundColor = 'green';
}
I don't know what you are trying to count with your counter function, so I can't fix that.
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
the user need to write the name of the animal, and I need to output the name+animalCode connected.
For some reason I am not getting any output.
Here is the code:
var str = "Cow12,Dog3,Cat721,Lion532";
var getInput = document.getElementById("inp1");
var getSubmit = document.getElementById("subm1");
getSubmit.onclick = function() {
var input = getInput;
var firstPlace = str.indexOf(input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
};
<form>
<input id="inp1" type="text">
<input id="subm1" type="submit">
</form>
<p id="print"></p>
Thank you very much for the help ! :)
You are just missing the .value part.
var str = "Cow12,Dog3,Cat721,Lion532";
var getInput = document.getElementById("inp1");
var getSubmit = document.getElementById("subm1");
getSubmit.onclick = function(event) {
event.preventDefault();
var input = getInput.value;
var firstPlace = str.indexOf(input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
};
<form>
<input id="inp1" type="text">
<input id="subm1" type="submit">
</form>
<p id="print"></p>
Make the following change :
Remove form tag as there is no need for that.
var str = "Cow12,Dog3,Cat721,Lion532";
function getSubmit()
{
var input = document.getElementById("inp1").value;
var firstPlace = str.indexOf("",input);
var numPlace = str.indexOf(",", firstPlace);
var newWord = str.slice(firstPlace, numPlace);
document.getElementById("print").innerHTML = newWord;
}
<input id="inp1" type="text">
<button id="subm1" onclick="getSubmit()">Submit</button>
<p id="print"></p>
I am trying to hide/show the plain text of a hashing function, I have been able to hide the input field but i have not been able to hide/show the plain text, the webpage has a input field and under that is the text that i am typing, then there is the hashed text, i am trying to replace the plain text with bullets.
I tried hiding it by counting the number of characters in the field and then repeating the bullet that many times. but now the page does not function at all.
<!DOCTYPE html>
<html>
<body>
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input
size="80"
input type="text"
rows="7"
id="edValue"
type="text"
onKeyPress="edValueKeyPress()
"onKeyUp="edValueKeyPress()">
<p id="string">Original text: </p>
<p id="lblValue">The SHA256 hash is: </p>
<script type="text/javascript" src="sha256.js">
</script>
<script type="text/javascript">
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The SHA256 hash is: "+sha256_digest(s);
var TheText = document.getElementById("string");
TheText.innerText = "Original text: "+s;
}
function toggleType() {
var obj = document.getElementById('edValue');
if (obj.type == 'password') {
obj.type = 'text';
} else {
obj.type = 'password';
repeat();
}
}
function repeat() {
var length = this.value.length;
var count = document.getElementById("edValue");
String.prototype.repeat = function(n) {
return new Array(1 + n).join(this);
var TheText = document.getElementById("string");
TheText.innerText = "*".repeat(count);
}
</script>
</body>
</html>
Just use a regex:
w/ jQuery:
$('YOURELEMENT').html($('div').html().replace(/./g, '*'));
without:
var text = document.getElementById('YOURELEMENT').innerText;
document.getElementById('string').innerHTML = text.replace(/./g, '*')
To toggle :
Html input
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input id="password" type="password" />
The javascript
function toggleType(){
var inputEl = document.getElementById('password');
if(inputEl.type != "text"){
inputEl.type = "text";
}else{
inputEl.type = "password";
}
}
Working example: http://jsfiddle.net/3MRAX/1/
Sorry about this, OP, but I tried :( This is as far as I got.
Javascript
function edValueKeyPress()
{
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
var hashes = s.hashCode;
lblValue.innerHTML = "The SHA256 hash is: " + hashes;
var text = document.getElementById("string");
text.innerHTML = "Original text: " + s;
}
function toggleType() {
var obj = document.getElementById('edValue');
if (obj.type == 'password') {
obj.type = 'text';
} else if(obj.type == 'text'){
obj.type = 'password';
}
}
HTML
<input
name="show password"
type="checkbox"
checked="checked"
onclick="toggleType();" />
<input
size="80"
type="text"
rows="7"
id="edValue"
type="text"
onkeyup="edValueKeyPress();">
<p id="string">Original text: </p>
<p id="lblValue">The SHA256 hash is: </p>