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>
Related
How can I make this code work well with the list printing the result on the same line.
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button onclick="submitText()">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
mainBody.innerHTML = '<li></li>'
const text = document.getElementById("toDo").value;
const myText = document.createTextNode(text);
mainBody.appendChild(myText);
}
</script>
</body>
</html>
Few things:
You overwrite the contents of the previous list when you do mainBody.innerHTML = '<li></li>'.
It is not semantically correct to add a text node to an ordered list. Instead, create a li element and append the text node to the li.
Try this instead:
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button onclick="submitText()">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
const text = document.getElementById("toDo").value;
const myText = document.createElement("li");
myText.appendChild(document.createTextNode(text));
mainBody.appendChild(myText);
}
</script>
</body>
</html>
Added few things:
remove the value of input when button is clicked
check if length of input is greeter then 1
event listener when enter key is pressed
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button id="btn">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
var input = document.getElementById("toDo")
if(input.value.length < 1 || input.value.replaceAll(" ", "") < 1) return; // check if the input value length is greeter then 1 character
const myText = document.createElement("li");
myText.appendChild(document.createTextNode(input.value));
mainBody.appendChild(myText);
input.value = ''; // clear the value input
}
document.getElementById("btn").addEventListener("click", submitText); // save the input value when button is clicked
document.getElementById("toDo").addEventListener('keypress', function (e) {
if (e.key === 'Enter') submitText();
}); // save the input value when enter key is pressed
</script>
</body>
</html>
Change
mainBody.innerHTML = '<li></li>'
to
mainBody.innerHTML += '<li></li>'
Here is what is needed to do:
<input type="text" id="main" placeholder="Put URL Here">
Every time the User Presses enter (or a Button on side of screen) I need Jquery to create:
<input type="hidden" id="url_1" readonly value='<-- input value from main-->'>
<!-- user adds another to #main -->
<input type="hidden" id="url_2" readonly value='<-- input value from main-->'>
<!-- etc -->
Here is what I got So far (only using HTML)
<figure class="mb-4">
<input type="text" name="" id="" placeholder="Image URL">
<button id="addimage">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
For the Upload Image button, It submits a Image to my PHP upload image, and just returns the URL to the image
This will append the hidden inputs to the end of your <form> tag. It also keeps an array of urls in case that's useful. For this snippet, it shows the array in a div.
let urls = [], limit = 2, main, addButton, resetButton
window.addEventListener('load', () => {
main = document.querySelector('#main'),
addButton = document.querySelector('[data-url-saver]'),
resetButton = document.querySelector('[data-url-reset]');
addButton.addEventListener('click', () => saveURL())
resetButton.addEventListener('click', () => reset())
})
const saveURL = () => {
let u = main.value;
urls.push(u);
let h = `<input type="hidden" data-url-hidden id="url_${urls.length}" readonly value=${u} />`
document.querySelector('form').insertAdjacentHTML('beforeend', h);
main.value = "";
let de = document.querySelector('#debug');
de.innerHTML = urls.join(", ");
if (urls.length >= limit) {
addButton.setAttribute('disabled', 'disabled');
main.setAttribute('disabled', 'disabled');
main.setAttribute('placeholder', 'Maximum URLs accepted')
}
}
const reset = () => {
urls = [];
document.querySelectorAll('[data-url-hidden]').forEach(e => e.parentNode.removeChild(e));
addButton.removeAttribute('disabled');
main.removeAttribute('disabled');
document.querySelector('#debug').innerHTML = "";
}
<form>
<input type="text" id="main" placeholder="Put URL Here">
<button data-url-saver type='button'>enter</button>
<button data-url-reset type='button'>reset</button>
</form>
<div id='debug'></div>
Create a div for hidden urls like
<div id="urls"></div>
try in jquery
var counter = 1;
$('#main').keypress(function (e) {
if(e.which== 13){ // enter key code
var url = $('#main').val();
$('#urls').append('<input type="hidden" id="url_'+ counter +'" readonly value="' + url + '" >');
$('#main').val(''); //clearing the input
counter++;
}
});
If you want to add ascending URL and if you have the link, then you can use the function below.
function addImage(){
var link = document.querySelector('#main').value;
var all_links = document.getElementById('all_urls');
if (link.length > 0){
code = `
<input type="hidden" id="url_${all_links.children.length}" value="${link}"/>
`
all_links.innerHTML += code;
console.log(document.getElementById('all_urls'))
}
}
<figure class="mb-4">
<input type="text" id="main" placeholder="Put URL Here">
<div id="all_urls">
<!--All the links are added here-->
</div>
<button id="addimage" onclick="addImage()">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
In jQuery
// Cache some elements
const div = $('div');
const main = $('#main');
$('button').click(() => {
// Grab the value
const val = main.val();
// Create the id based on the current
// number of inputs
const id = div.find('input').length + 1;
// Append the new input
div.append(`<input readonly id="url_${id}" value="${val}" />`);
// Reset the main input
main.val('');
});
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
And the equivalent in vanilla JS:
// Cache some elements
const div = document.querySelector('div');
const main = document.querySelector('#main');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false)
function handleClick() {
// Create the id based on the current
// number of inputs
const id = div.querySelectorAll('input').length + 1;
const html = `<input readonly id="url_${id}" value="${main.value}" />`;
// Append the new input
div.insertAdjacentHTML('beforeend', html);
// Reset the main input
main.value = '';
};
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
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);
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;
}
i have a div tag where i entered sime text. now i want, as the user clicks on the button, a cursor should pop-up and user edit the text. as user clicks on save button the text should displays min the div tag inplace of old text..
my div tag is as:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" type="hidden" onclick="edit1();"/>
Div Tag
</div>
here i want to have a cursor when user clicks edit button and as user ebters text and clicks save the ' div tag ' text should get replaced by new text..
how this can be done using java script..
What you are doing makes no sense from either a technical or semantic view. Just use a textarea.
<textarea id="content" value="sample text" disabled="true" /></textarea>
<input type="button" id="edit" value="edit" onClick="edit()" />
<input type="button" id="save" value="save" onClick="save()" />
function edit() {
document.getElementById('edit').style.display = 'none';
document.getElementById('save').style.display = 'block';
document.getElementById('content').disabled = false;
}
function save() {
document.getElementById('save').style.display = 'none';
document.getElementById('edit').style.display = 'block';
document.getElementById('content').disabled = true;
}
#content {
width: 300px;
height: 200px;
}
#edit, #save {
padding: 2px;
width: 50px;
}
#save {
display: none;
}
Example here
// This sample code is with prompt (popup input) if you want to use textbox, the code to be replaced accordingly.
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="btndiv" style='display:hidden' onclick="edit1();"/>
<div id="text1"> </div>
</div>
<script>
function button1()
{
document.getElementById ("btndiv").display = '';
}
function edit1()
{
var val = prompt ("Enter some value");
document.getElementById ("text1").innerHTML = val;
document.getElementById ("btndiv").display = 'hidden';
}
</script>
I suggest creating an internal div enclosing just the text, like this:
<div id="topdiv" style="color:Blue" onmouseover="button1();">
<input type="button" id="editbtndiv" onclick="edit1();" value="edit"/>
<input type="button" id="savebtndiv" onclick="save1();" value="save"/>
<input type="text" id="inputdiv" style="display:none;" />
<div id="divtext"> Div Tag </div>
</div>
Then, to display the input field and hide the text:
var editObj = document.getElementById("editbtndiv");
editObj.style.display = "none";
var saveObj = document.getElementById("savebtndiv");
saveObj.style.display = "block";
var inputObj = document.getElementById("inputdiv");
inputObj.style.display = "block";
var txtObj = document.getElementById("divtext");
txtObj.style.display = "none";
Then user does his job, clicks save and you can hide the input field and show the text:
var editObj = document.getElementById("editbtndiv");
editObj.style.display = "block";
var saveObj = document.getElementById("savebtndiv");
saveObj.style.display = "none";
var inputObj = document.getElementById("inputdiv");
inputObj.style.display = "none";
var txtObj = document.getElementById("divtext");
txtObj.value = divObj.value;
txtObj.style.display = "block";