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>
Related
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
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.
I am trying to create an add more button which will create a new input field. However, I would like to have an unique name set for it.
I tried to search up for an answer, but this does not answer my question.
So, basically what I tried to make my namefield unique is to use the php method rand(). The concept is that - when the add more button is clicked, it will have a name attached to the number given to me by rand().
However, what happens is that it takes the value generated by rand() and applies it to all the names of all the inputs generated.
This is my code and what I tried:
HTML:
<div class="field_wrapper">
<div>
<input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>
Add More
</div>
</div>
JQUERY / JAVASCRIPT:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 100; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>Remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
As you can see, the first field generates the number as intended. If you click on the add more, the second field does create an unique number. However, if you click add more once again, the third field copies the same name as the 2nd field.
How do I go about achieving what I want and why is rand() not generating a new code?
Also, does rand() guarantee me that it will be an unique ID or is there a chance for it to repeat the same number?
If it does repeat, then what would be the best approach to take to make it as unique as possible?
If you generate random name with PHP it is done once on the server. Your JS code then copies the same element. What you need is to generate unique names with js.
Avoid random if you can, theoretically, you can hit the same number and run into mysterious bugs.
var generateField = function(name)
{
return '<div><input type="text" name="'+name+'" value=""/>Remove</div>'; //New input field html
}
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(generateField('field_name['+x+']' ) ); //Add field html
}
});
Random does not necessarily mean unique, even if collisions would be extremely rare. This solution simply increments a totalFieldsCreated variable to get the next unique number (up to the maximum value JavaScript can provide.)
The new fields are created dynamically instead of using a fixed string of HTML. (This technique is more flexible.)
$(document).ready(function() {
// Defines global identifiers
let
currentFieldCount = 1,
totalFieldsCreated = 1;
const
maxFieldCount = 100,
addButton = $('.add_button'),
wrapper = $('.field_wrapper');
// Calls `addField` when addButton is clicked
$(addButton).click(addField);
// Executes anonymous function when `Remove` is clicked, which removes
// the parent div, and decrements (and logs) `currentFieldCount`
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
currentFieldCount--;
console.log(`currentFieldCount: ${currentFieldCount}`);
});
// Defines the `addField` function
function addField(){
// Makes sure that `currentFieldCount` and `totalFieldsCreated`
// are not at maximum before proceeding
if(
currentFieldCount < maxFieldCount &&
totalFieldsCreated < Number.MAX_VALUE
){
// Creates an input element, increments `totalFieldsCreated`,
// and uses the incremented value in the input's `name` attribute
const input = document.createElement("input");
input.type = "text";
input.name = "field" + ++totalFieldsCreated;
input.value = "";
// Creates an anchor element with the `remove_button` class
const a = document.createElement("a");
a.href = "javascript:void(0);";
a.classList.add("remove_button");
a.title = "remove";
a.innerHTML = "Remove";
// Adds the new elements to the DOM, and increments `currentFieldCount`
const div = document.createElement("div");
div.appendChild(input);
div.appendChild(a);
$(wrapper).append(div);
currentFieldCount++;
// Logs the new values of both variables
console.log(
`currentFieldCount: ${currentFieldCount},`,
`totalFieldsCreated ${totalFieldsCreated}`
);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" name="field1" value="" />
Add More
</div>
</div>
Try Math.random() in js rather than rand() in php ,Math.floor(Math.random()*90000) + 10000 will generate a five digit random number , Hope this helps
$('.rand').attr('name',"fields["+Math.floor(Math.random()*90000) + 10000+"]")
$('.add_button').click(function(e){
$('.field_wrapper').append('<div><input type="text" name=fields['+Math.floor(Math.random()*90000) + 10000+'] value=""/>Remove</div>')
})
$(document).on('click','.remove_button',function(e){
$(this).parent().remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" class="rand" value=""/>
Add More
</div>
</div>
$(document).ready(function () {
var userSites = newArray();
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 5; //initial text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) {
x++; //text box increment
$(wrapper).append('<div><input type="text" name ="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
I have this code, because I want to have a lot of user inputs. However, once the user inputs this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet, is that possible as well?
However, now that the user has input this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet?
When the form is submitted, the event handler, collectData gathers the text in each <input> and uses the push method to populate an array. This array is then stored in a hidden <input> and that data is then extracted by the form which then posts to the server.
I don't know much about Java applets but I got you this far. I suggest you ask about Java in a new question. Your tags are of a JavaScript/jQuery nature.
My demo actually functions with a test server so once submitted, the server will respond with the data that was posted to it.
This works: http://plnkr.co/edit/seD0L3oI7dTnXQrrFZPl?p=preview
Added Code
form.addEventListener('submit', collectData, false);
function collectData(e) {
var userSites = [];
var cache = document.getElementById('cache');
var z = 0;
while (z < max_fields) {
z++;
var data = inputs[z].val();
userSites.push(data);
}
e.stopPropagation();
cache.value = userSites;
}
});
Create an Array object in your one of you script tags :
<script type="text/javascript" >
var myArr=new Array();
</script>
Now add onchange to your inputs also update myArr :
$(wrapper).append('<div><input type="text" name ="myText'+x.toString()+'" onchange="myArr.push(this.value);document.getElementById('myArrInput').value=JSON.stringify(myArr);" /><a href="#" class="remove_field" onclick="myArr['+x.toString()+'].value=null;document.getElementById('myArrInput').value=JSON.stringify(myArr);" >Remove</a></div>');
Add this hiddenField to your page to send myArr to you applet as JSON string:
<input id="myArrInput" type="hidden" name="myArray" value="" />
In server you have to convert myArray Json string to object.
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'))