How to link a button and input field - javascript

How do I link a button to an input field? I am trying to create something so that when I click on the button, it will add what was in the text field, to an array (shown below)
const userTags = [];
function addTags(event) {
userTags.push(event.target.__ what do I even put here to get the input data? __)
}
<label>
Tags: <input type="text" name="todoTags"/> <button>Create new tag</button>
</label>
Again, I am trying to link up the button so that when I click it, it will grab the data from the input field, and add that data to the 'userTag' array with the addTags() function.

You can use the event target within your callback function to get the label using const parent = e.target.closest('label'), then use querySelector() to get the input element that is grouped under that label tag using const input = parent.querySelector('input') then set a variable to that value like const inputValue = input.value, then push the value into your array.
Your callback function is placed into an event listener for click.
const btn = document.querySelector('.btn')
const userTags = []
function getValue(e) {
// get the label by traversing up the DOM tree to the closest label element
const parent = e.target.closest('label')
// get the input that lives inside the label element using querySelector
const input = parent.querySelector('input')
// get the inputs value and assign to variable
const inputValue = input.value
// only push values that are not empty
if (inputValue !== "") {
userTags.push(inputValue)
}
console.log(userTags)
}
//event listener for click on btn element
btn.addEventListener('click', getValue)
<label>
Tags: <input type="text" name="todoTags"/> <button class="btn">Create new tag</button>
</label>

let valueArray = []
function getValue(){
let value = document.getElementById("input").value
valueArray.push(value)
document.getElementById("Messages").innerHTML = valueArray
}
<body>
<input type="text" id="input">
<button onclick="getValue()">Click</button>
<div id="Messages"></div>
</body>
Get the element with document.getElementById and then take its value
document.getElementById("Put Id In Here").value

Related

How to check users inputed string is in the array in javascript?

I want my user type a string in input box of html,than i want to check if it is in the array of items or not.I am using this JS code:
var items = ["apple"];
var userInput = document.getElementById("input").value;
function lol() {
document.write(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>
But when i run this every time it gives false.
You need to move
var userInput = document.getElementById("input").value;
into the function, because it assigns the value at start and is never changing.
var items = ["apple"];
function lol() {
var userInput = document.getElementById("input").value;
console.log(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>
You can add an onChange event listener for the input field and change the userInput value for every change in the input field.
var items = ["apple"];
var userInput = document.getElementById("input").value;
function onChangeUserInput (event) {
console.log(event.target.value);
userInput = event.target.value;
}
document.getElementById("input").addEventListener('change', onChangeUserInput);
function lol() {
document.write(items.includes(userInput));
}
<input type="text" id="input">
<button onclick="lol()">check</button>
I tried to replicate the error. This is my code -
var items = ['apple', 'orange', 'mango'];
var input = 'apple';
console.log(items.includes('apple'));
It works as expected. The problem is that you have called the lol() function in the button. So, the function is called when the page loads and not when it is clicked. Another thing is that you have to move the line in which you get user input into the lol() function.

How to get value from an input field in javascript?

I tried .value , .textContent , innerText .... But nothing worked....
Below is my html
var input = document.getElementById('input').value
var button = document.getElementById('submit')
button.addEventListener('click', () => {
console.log(input) /// Output is always blank
})
<div class="input-section">
<input type="text" id="input" placeholder="Enter the word">
<button id="submit">Find</button>
</div>
You need to read the value property when the event fires, not before it.
let input = document.getElementById('input');
let button = document.getElementById('submit');
button.addEventListener('click',()=>{
console.log(input.value);
})
The reason why it is blank is because, you're initializing the input variable with the initial value inside input, i.e. nothing.
When you click the button, you want the "current" value of input, which means that you'd have to find value on each button click.
Do it like this :
var button = document.getElementById('submit')
button.addEventListener('click', () => {
var input = document.getElementById('input').value;
console.log(input);
})
<div class="input-section">
<input type="text" id="input" placeholder="Enter the word">
<button id="submit">Find</button>
</div>

get an element id and then use it in a getElmentByID to trigger a function on click

function getId(e){
var xid = e.target.id;
console.log(xid);
}
<form onclick="getId(event)">
<label for="name" id="I am an Span">Nombre</label><br>
<input type="text" name="name" id="tbx_nombre"> <br>
<span id="nombre"></span> <br>
</form>
<div id="result"></div>
When the user click on a texbox the function gets the id of the element, then the deleteSpan method is call with the splitted id of the textbox which is now the id of the span to be changed to an emply string.
I get this error Cannot set property 'onclick' of null at getId
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name"></span>
...MORE INPUTS AND SPAN TAGS...
</form>
JS
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
document.getElementById(xid).onclick = function(){deleteSpan(spanId)};
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
You are getting that error because when you try to set the click handler on the span by ID, you don't currently have the correct ID. It's null, because the click target is currently the form (which doesn't have an ID) instead of the input.
As others mentioned, the click event listener should be attached to the input.
But you also don't need to set a separate click handler within getId--you can just call deleteSpan in the getId function. In fact, if you set it inside another handler like you have, it won't work the first time (unless that's your desired outcome).
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form>
<input onclick="getId(event)" type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>
onclick attribute event handler should be at input instead of form
<form>
<input type="text" name="name" id="tbx_name" onclick="getId(event)"><br>
<span id="name"></span>
</form>
or even better, use addEventListener for the inputs which have id format as tbx_{{value}}
var allInputs = document.querySelectorAll("input[id^='tbx_']");
allInputs.forEach( s => s.addEventListener( "click", e => getId ));
You can invoke above code when the form has loaded (at document load or window load).
You have to set the attribute onclick in input instead of form to get the expected id. Otherwise you have to check if the target node is INPUT or not:
function getId(e){
if(e.target.nodeName == 'INPUT'){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>

Add search field result to an empty array

Every time a user types something into a search field, I want it to be added to an empty array I've created. For some reason, my current code only adds an empty string to the array but not the string itself:
Javascript
var myArray=[];
var submit = document.getElementById("submit");
var result = document.getElementById("result").value;
submit.addEventListener("click", function() {
myArray.push(result);
})
HTML
<input id="result" type="text"><button id="submit">Submit</button>

How to save the values in existing input fields when adding a new one?

This is what my program's body looks like:
<form id = "input">
<input id = "0" >
</form>
<p onclick = "add()"> Add Another</p>
And on clicking the above The following function is executed:
var inputArea = document.getElementById("input");
next = 1;
function add(){
inputArea.innerHTML+= " <input id = " + next+ ">" ;
Where next is the id of new input field. In this case, since 0 already exists so value of next is 1.
One problem that I am encountering with this is that after adding a new input field, the values in all existing input fields are lost. How to save these values? My attempt is to place this code in function add():
for (i=0;i<next;i++)
{inputs[i] = document.getElementById(i);
inputV[i]= inputs[i].value;
inputs[i].value = inputV[i];}
But this does not works..
var inputArea = document.getElementById("input");
next = 1;
function add(){
inputArea.innerHTML+= " <input id = " + next+ ">" ;
var inputs = new Array();
var inputV = new Array();
for (i=0;i<next;i++)
{inputs[i] = document.getElementById(i);
inputV[i]= inputs[i].value;
inputs[i].value = inputV[i];}
next++;
}
<form id = "input">
<input id = "0" >
</form>
<p onclick = "add()"> Add Another</p>
You may want to dynamically add elements to your DOM tree like so
function add() {
var form = document.getElementById("input");
var input = document.createElement("input");
form.appendChild(input);
}
The problem with what you're doing is that when you write inside an input field, the changes are not represented in the HTML code, only in the memory of the browser. Thus if you add text through to code to form.innerHTML, the browser is going to reinterpret the text inside the form which will be
<input id="0"> <input id="1"> ...
and this will result in two empty input of type text being displayed.
Edit: you can then add your id tag via
function add() {
var form = document.getElementById("input");
var input = document.createElement("input");
input.id = someValue;
form.appendChild(input);
}
N.B. please indent your code in a somewhat logical manner.
The reason this is happening is that the dom, or more specifically inputArea's innerHtml doesnt get changed when you type into a form field. And what youre doing is resetting the innerHTML with a blank input BEFORE youre capturing the values.
so whats going on is you have HTML like this:
<input id='0' />
then type into the form so that it behaves like:
<input id='0' value='foo' />
but thats not what the innerHTML actual is. its still <input id='0' /> because the value is kept in memory not on the dom.
if you want to add new elements to the form, you need to use appendChild instead
so convert
inputArea.innerHTML+= " <input id = " + next+ ">"
to
inputArea.appendChild(document.createElement('input'))

Categories

Resources