I've just started learning javascript. I'm trying to create a condition that will turn some text red or blue depending on a number entered into a form, but it's not working and I can't figure out why. Every time the text turns blue no matter what number is entered. It should turn red if the number entered is less than 50. This is what I have:
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
});
var input = document.getElementById("input");
var submit = document.getElementById("submit");
submit.onclick = function() {
if (input >= 50) {
document.getElementById("color").style.color = "red";
} else {
document.getElementById("color").style.color = "blue";
};
}
<h3 id="color">Conditional Example</h3>
<form name="form">
<input type="text" id="input"><br>
<button type="submit" id="submit">Submit</button>
</form>
You need the value of the input element.
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
});
var submit = document.getElementById("submit");
submit.onclick = function(event) {
// getting the value after click of the button
var input = document.getElementById("input").value;
if (input >= 50) {
document.getElementById("color").style.color = "red";
} else {
document.getElementById("color").style.color = "blue";
};
}
<h3 id="color">Conditional Example</h3>
<form name="form">
<input type="text" id="input"><br>
<button type="submit" id="submit">Submit</button>
</form>
document.getElementById("input") gets the actual element. You want the value of that element, so use document.getElementById("input").value. You also want to check the value on every click, so you need to move that line within your click handler:
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
});
var submit = document.getElementById("submit");
submit.onclick = function() {
var input = parseInt( document.getElementById("input").value, 10 );
if (input >= 50) {
document.getElementById("color").style.color = "red";
} else {
document.getElementById("color").style.color = "blue";
};
}
<h3 id="color">Conditional Example</h3>
<form name="form">
<input type="text" id="input"><br>
<button type="submit" id="submit">Submit</button>
</form>
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>
I have a form that i enter the number of element then the text then the type div or section
and i click create i should remove the older div or section and create the new one
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
The problem is that the div or section appear but than disappear quickly i'm checking if the field are empty and if the field element number > 0 than i create the element that should appear in the result div
how can i solve this problem
The problem with your code is that you aren't preventing the <form> from refreshing the page.
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
You use the above if statement to prevent the <form>'s default behaviour, but you set all those variables to true after creating your elements.
validElement = true;
validText = true;
validType = true;
So your script basically creates the elements and then the form refreshes the page.
Moving e.preventDefault(); outside of its if block would fix your immediate problem.
I would personally call e.preventDefault(); regardless of whether the users put in valid data, as a page refresh seems unneccesary in either case.
As for how to clear your results div, here is an elaborate post describing several ways of doing it.
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
// Clear the Results Container
while (result.firstChild) {
result.removeChild(result.lastChild);
}
// Repopulate the Results Container
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
e.preventDefault();
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
enter image description hereI have a button that permit to add checkbox element dynamically,
function addCheck() {
var checkinput = document.createElement('input')
var form = document.getElementById('form')
check.setAttribute('type', 'checkbox')
check.setAttribute('name', 'check')
form.appendChild(checkinput)
}
I want to count how many the user created a new Element whenever he presses the button
var count=0;
function addCheck() {
let pos= document.getElementById("dynamic-checkbox");
var checkinput = document.createElement("input");
check.setAttribute("type", "checkbox");
check.setAttribute("name", "rep");
pos.appendChild(check);
count++;
Here's an alternative to using a counter variable, or checking the length of the number of existing elements in the DOM. You initially set up the counter element with the textContent set as zero, and then with each call of the function set that content to whatever the current content is (coerced from a string to a number) plus 1.
// Cache the elements we reuse
const form = document.querySelector('form');
const button = document.querySelector('button');
const counter = document.querySelector('#counter');
button.addEventListener('click', addCheck, false);
function addCheck() {
const checkinput = document.createElement('input');
checkinput.setAttribute('type', 'checkbox');
checkinput.setAttribute('name', 'check');
form.appendChild(checkinput);
counter.textContent = Number(counter.textContent) + 1;
}
<div id="counter">0</div>
<button>Add checkbox</button>
<form></form>
You can use querySelectorAll() by passing the input type as the selector and take the length:
var count = form.querySelectorAll('input[type=checkbox]').length;
var form= document.getElementById("form");
function addCheck() {
var checkinput = document.createElement("input");
checkinput.setAttribute("type", "checkbox");
checkinput.setAttribute("name", "check");
form.appendChild(checkinput);
var count = form.querySelectorAll('input[type=checkbox]').length;
console.log('Total Checkbox: ' +count);
}
<form id="form"></form>
<button type="btn" onclick="addCheck()">Add</button>
You can also maintain a variable as counter:
var form= document.getElementById("form");
var count = 0;
function addCheck() {
var checkinput = document.createElement("input");
checkinput.setAttribute("type", "checkbox");
checkinput.setAttribute("name", "check");
form.appendChild(checkinput);
count++;
console.log('Total Checkbox: ' +count);
}
<form id="form"></form>
<button type="btn" onclick="addCheck()">Add</button>
Just add a counter and increment it on button click. While setting attribute you have used the name of the variable in which the element is stored as check, but it should be checkinput
var count = 0;
var total=0;
function addCheck() {
var checkinput = document.createElement('input')
var form = document.getElementById('form')
checkinput.setAttribute('type', 'checkbox')
checkinput.setAttribute('name', 'check')
form.appendChild(checkinput)
count++;
total=count+2;
console.log('Number of checkboxes created by the user:' + count)
console.log( 'Total checkboxes in the form:' + total)
}
<button onclick="addCheck()">click</button>
<form id="form">
<input type="checkbox" name="check">
<input type="checkbox" name="check">
</form>
I have simple code, in input user inputs number and it must print the numbers until the input is not equal to zero.
And the problem is when i submit value, page stops responding
Here is how my code looks like:
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
while(input !== 0) {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
The value property of input is a string.
You must compare with the correct type:
while (input !== '0')
or
while (input != 0)
----- edit -----
Consider changing the while to an if, otherwise it will print any number different of 0 indefinitely.
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if(input !== '0') {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
You need to make two changes
Change type attribute from text to number
Change from while to if
Demo
window.onload = function()
{
var btn = document.getElementsByClassName('btn')[0];
function printInput()
{
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if (input !== 0)
{
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input + '<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="number" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
I'm trying to get this form to change label color after submission if the field is empty and then return back to normal when the field is filled in.
It's behaviour would be something similar to:
Onsubmit validate change background requried fields?
Except I can't figure out how to link the inputs to the labels. I'm using the jsFiddle from the link above at:
http://jsfiddle.net/interdream/cpG2r/7/
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
My JavaScript isn't so good. Please help!
Here is your Working sample</>
You should look around Knockoutjs style binding with dom value.
you could add label tags, like:
<form action="" id="myForm">
<label for="field1">Required field:</label> <input type="text" name="field1" class="required" /><br />
<label for="field2">Required field 2:</label> <input type="text" name="field2" class="required" />
<input type="submit" value="Go" />
</form>
And in js part
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
var lbl = document.getElementsByTagName("label")[i]; //get label
if(!fields[i].value) {
lbl.style.color = "red";
console.log(lbl );
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
lbl.style.color = "black";
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
See : updated Fiddle
Try
<form action="" id="myForm">
<label>Required field: </label><input type="text" class="required" /><br />
<label>Required field 2: </label><input type="text" class="required" />
<input type="submit" value="Go" />
</form>
And
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
var prev = fields[i].previousSibling;
while(!/label/i.test(prev.tagName)){
prev = prev.previousSibling;
}
prev.style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
Demo: Fiddle
You can use jquery validation Plugin ... it has support for all types of validations as well as changing label colors & Can display suitable error messages
Here is very simple, smart yet effective way to doing this by using amazing knockout binding here is working sample :JsFiddle Link
var viewModel = {
validation: ko.observable(function(){})
};