can I pass a js array into an input field - javascript

I'm trying to pass an array to an input field in a chat. The array passed is after meeting certain conditions.
For example in this code below, the array comes from a loop over another div element.
So when the user selects an option, based on the selection, the array is passed as an answer.
This is my code below;
<select name="result" id="result" dataquestion="Click on the button below to know your answer.">
<option value="my result">Yes</option>
<option value="no result">No</option>
</select>
<div data-fork="result">
<div data-case="my result" id="responses">
<input type="text" data-answer="[]">
</div>
<div data-case="no result" id="response">
<input name="thought" data-answer="[]">
</div>
</div>
<div id="target">i love a cat</div>
<script type="text/javascript">
var array1 = []
//var array1 = ["i love a cat"]
$("#target").each(function() {
array1.push($(this).html());
});
var array2 = ["bat", "cat", "dog"];
function getMatch(a, b) {
var matches = [];
var response = "You got it right"
for ( var i = 0; i < a.length; i++ ) {
for ( var e = 0; e < b.length; e++ ) {
//if ( a[i] === b[e] ) matches.push( a[i] );
if ( a[i] === b[e] ) matches.push(response);
}
}
return Array.from(new Set(matches));
}
document.getElementById("target").innerHTML = getMatch(array1, array2);
</script>
SO in this js snippet, instead of passing the value to id=#target, it goes to the 'data-answer="[]"'.
Is there a way to achieve this?
Kind regards

Related

(JS) Remove an option from select box JUST ONCE after calling function

I have this code where I want to add text to the select box when calling a function via clicking an input button.
I want the select box to have a default text when the page is loaded and no value is added to the array. And I want this text to vanish but I could still add many values from the input box and make them show on the select box.
So I made the input and select box with the following:
let num = document.querySelector('input#numtxt')
let lista = document.querySelector('select#seltxt')
let res = document.querySelector('div#res')
let valores = []
function adicionar() {
if (isNumero(num.value) && !inLista(num.value, valores)) {
lista.options[0] = null //
valores.push(Number(num.value))
let item = document.createElement('option')
item.text = `Valor ${num.value} adicionado.`
lista.appendChild(item)
} else {
window.alert('Valor inválido ou já existe!')
}
}
<div>
<p>TYpe a number between 1 and 100: <input type="number" name="num1" id="numtxt">
<input type="button" value="Adicionar" onclick="adicionar()"></p>
</div>
<div>
<p>
<select name="sel1" id="seltxt" size="10">
<option>Type a number above!</option>
</select>
</p>
<p><input type="button" value="End" onclick="finalizar()"></p>
</div>
I've tried a lot of commands with boxvar.options[0] = null and boxvar.remove(0)but they all kept removing the first value which I need for the program.
Any sugestions?
let num = document.querySelector('input#numtxt')
let lista = document.querySelector('select#seltxt')
let res = document.querySelector('div#res')
let valores = []
function adicionar() {
if (isNumero(num.value) && !inLista(num.value, valores)) {
if(!valores.length) {
// If there are no values on list, delete whatever is inside of select
lista.innerHTML = ''
}
valores.push(Number(num.value))
let item = document.createElement('option')
item.text = `Valor ${num.value} adicionado.`
lista.appendChild(item)
} else {
window.alert('Valor inválido ou já existe!')
}
}
This is slightly verbose for clarity - if we add a data attribute we can filter on that and remove it if it exists. We can also filter by values and not add if the new one exists (it could be a data attribute if you do not want to set the value.
let lista = document.querySelector('#seltxt');
let res = document.querySelector('#res');
let valores = [];
function adicionar() {
let num = document.querySelector('#numtxt');
let opts = [...lista.options].filter((element, index) => {
return element.dataset.default == "default";
});
console.log(opts);
if (opts.length) {
opts[0].remove();
}
let newValue = Number(num.value);
// now if it already exists, don't add it
let matchOpt = [...lista.options].filter((element, index) => {
return element.value == newValue;
});
// we already have it so jump back out
if (matchOpt.length) {
return;
}
valores.push(newValue);
let item = document.createElement('option');
item.text = `Valor ${num.value} adicionado.`;
item.value = newValue;
lista.appendChild(item);
}
<div>
<p>Type a number between 1 and 100: <input type="number" name="num1" id="numtxt">
<input type="button" value="Adicionar" onclick="adicionar()"></p>
</div>
<div>
<p>
<select name="sel1" id="seltxt" size="10">
<option data-default="default">Type a number above!</option>
</select>
</p>
<p><input type="button" value="End" onclick="finalizar()"></p>
</div>

Javascript using For loop for false

I'm learning now for loops, and as an example I was given in a game this (with '.result-paras' being p classes):
<div class="form">
<label for="guess-field">Enter a guess: </label>
<input type="text" id="guess-field" class="guess-field">
<input type="submit" value="Submit guess" class="guess-submit">
</div>
<div class="result-paras">
<p class="guesses"></p>
<p class="last-result"></p>
<p class="low-or-high"></p>
</div>
const resetParas = document.querySelectorAll('.result-paras');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
I want to try to copy it on an input type which I want to disable, meaning I want 2 input fields to be disabled using a loop and I'm having trouble getting it to work, would really appreciate your help:
const disableParas = document.querySelectorAll('.form');
for (let i = 0; i < disableParas ; i++ ) {
disableParas[i].disabled = false;
}
When using a for loop to iterate over a list like that, you often use it like this, counting up a variable up to the length of the list:
const disableParas = document.querySelectorAll('.form');
for (let i = 0 ; i < disableParas.length; i++ ) {
disableParas[i].disabled = false;
}
The first part of the for loop is what you do initially, the second part is the condition to stop the loop and the last part is executed each iteration of the loop.

Adding And Sorting Array Of Integers from html input field Using Javascript

The Task Is To Get 10 Values Of Array Through HTML Input Field
And Sort Them In Acceding Order
In Order To Append 10 Value's from Html Input field To JS Array I Created one input field which data is passed to array in js and Two labels to keep track of array using innerHTML Method
Note:- The Name Of Array Is itself declared array
whenever a button is hit the input value of html data is appended to js array
using id of input field
and the resulted array is shown to label list every time we insert a new digit to array
and the next label similar to this updates array lenght simantaeneously
to limit it upto 10 index i compare array.lenght with 10th value i.e. 9th index
Note:- Here Array index is starting from 0 so 9th index is 10th digit
But even Though Code Is Not Working Well
Here's my code looks like
HTML File
<div id='div3'>
<input type='number' id='ip1' placeholder='Enter values'></input>
<label id='list' >List values are:</label>
<button id='bt3' onClick='task()'>ADD Value</button>
<label id='len' >Length:</label>
</div>
JS FIle
var array =[];
function task()
{
let pr=array.length;
document.getElementById('len').innerHTML=pr;
if(array.length > 9)
{
let item = document.getElementById('task3val').value;
array.push(item);
document.getElementById('list').innerHTML=array;
}
if(array.length<=9)
{
array.sort(function(a, b){return b - a});
document.getElementById("list").innerHTML = array;
}
}
Please Give Insighful Answer
I have made few changes in your code, It should work for you now. in the above code, you were using the wrong id for the text box
HTML code
<div id='div3'>
<input type='number' id='ip1' placeholder='Enter values'></input>
<br/>
<label id='list' >List values are: </label>
<br/>
<button id='bt3' onClick='task()'>ADD Value</button>
<br/>
<label id='len' >Length:</label>
</div>
Jquery code
<script type="text/javascript">
var array =[];
function task()
{
if(array.length < 3)
{
let item = document.getElementById('ip1').value;
array.push(item);
document.getElementById('list').innerHTML = array.toString();
}
else
{
alert('Only 10 Items allowed!')
}
let pr=array.length;
document.getElementById('len').innerHTML=pr;
}
</script>
If I'm getting it right, this is your solution:
var array =[];
function task()
{
let item = document.getElementById('ip1').value;
array.push(item);
let pr=array.length;
document.getElementById('len').innerHTML= "Length: "+pr;
array.sort(function(a, b){return b - a});
document.getElementById("list").innerHTML = array;
if(pr>=10){
array.pop()
//This removes the last element,
//since it is always ordered, last element is always the smallest
}
}
<div id='div3'>
<input type='number' id='ip1' placeholder='Enter values'></input>
<label id='list' >List values are:</label>
<button id='bt3' onClick='task()'>ADD Value</button>
<label id='len' >Length:</label>
</div>
I am not sure what you were trying to do with that if statement, but the long story is you should first add the item in the array, then the length should return the correct length (so, 1 if there is 1 item, 2 if there are 2, etc.) and then re-order the array and print it on screen
EDIT: I guess you only want to keep the biggest 10 numbers at any time, so what we do is we simply remove the last element once pr reaches 10
this way ?
const
array = []
, arrLimit = 10
, in_ip1 = document.querySelector('#ip1')
, lb_list = document.querySelector('#list')
, bt_bt3 = document.querySelector('#bt3')
, lb_len = document.querySelector('#len')
, errors =
{ noVal : 'please enter a number value'
, outLimit : `Only ${arrLimit} Items allowed!`
, exist : 'value already entered !'
}
bt_bt3.onclick = () =>
{
let inVal = in_ip1.valueAsNumber
if ( isNaN(inVal) ) alert( errors.noVal )
else if (array.length >= arrLimit) alert( errors.outLimit )
else if (array.includes(inVal)) alert( errors.exist )
else
{
array.push( inVal )
array.sort((a,b)=>b-a) //.splice( arrLimit )
lb_list.textContent = array.join(', ')
lb_len.textContent = array.length
}
}
#div3 > * {
display : block;
float : left;
clear : left;
margin : .5em;
}
#list:before { content: 'List values are: ' }
#len:before { content: 'Length: ' }
<div id="div3">
<input id="ip1" type="number" placeholder="Enter values">
<label id="list" ></label>
<button id="bt3">ADD Value</button>
<label id="len" ></label>
</div>

Delete Child Span after Child Span Delete remaing Child auto rearrange why?

Here is my Javascript code:
function validspan() {
var data = document.querySelector('.keyword-input').value;
var nodes = document.querySelectorAll('.keywords-list span');
var str = Array.prototype.map.call(nodes, function(node) {
return node.textContent;
}).filter(a => !!a).join(",");
var arr = str.split(',');
for (var k = 0; k < arr.length; k++) {
if (data == arr[k]) {
alert("Don't Enter Same Skill");
let list = document.querySelector('.keywords-list');
let array = arr[k].indexOf(data);
list.removeChild(list.childNodes[array]);
return true;
} else {
alert('different values');
return false;
}
}
}
and html code where runtime spans create
<input type="text" class="keyword-input with-border #error('name') is-invalid #enderror" name="skills" placeholder="Add Skills">
<div class="invalid-feedback" style="color: red;font-size: 20px"></div>
<button type="button" class="keyword-input-button ripple-effect" onclick="validspan()"><i class="icon-material-outline-add" ></i></button>
</div>
<div class="keywords-list">
<!-- keywords go here -->
</div>
If value match then delete index but in this my code only 0 index
check and delete 0 idex. my requirment is when same value any index
then delete index
i guess you are looking for something like this?
(() => {
const btnEl = document.querySelector('#add_skill');
const inputEl = document.querySelector('#skills');
const resultsEl = document.querySelector('#keywords-list');
const arr = [];
arr.add = function(val) {
this.push(val);
resultsEl.innerHTML = arr.map(item => `<span>${val}</span>`).join('');
};
btnEl.addEventListener('click', (e) => {
let val = inputEl.value;
if (!val) {
console.error(`A value is required`);
return;
}
if (arr.includes(val)) {
console.error(`Don't Enter Same Skill`);
return;
}
arr.add(val);
});
})();
<input type="text" class="keyword-input with-border #error('name') is-invalid #enderror" id="skills" name="skills" placeholder="Add Skills">
<div class="invalid-feedback" style="color: red;font-size: 20px"></div>
<button type="button" id="add_skill" class="keyword-input-button ripple-effect"><i class="icon-material-outline-add" ></i>Add</button>
</div>
<div class="keywords-list" id="keywords-list">
<!-- keywords go here -->
</div>
in your for loop, you are terminating the execution directly and breaking from it by using the return keyword in both the if statement and the else statement, so basically what your code is doing is just testing the first index (0) and omitting all the other indexes!
you need to remove the return statements and then continue editing your code to handle other cases!
you can understand better about return inside a for loop with the answers in this question : question
hope that helped!

passing names into an array and sorting them

what im tryng to do is enter a first and last name into a textarea, once the "enter name" button is hit the names will go into an array, where they are sorted, then put back into a string and displayed in the "output" box. everytime a name is entered it will be added into the same array and sorted.
I was able to get the names into an array, and displayed in the output box, but i cant get it to add names to the list, or sort them alphabeticly. it just replaces them. I thought i could use push to add the names, but it doesnt seem to work. Any help would be very appreciated. Thanks in advance.
here is what i have so far:
<body>
<p>
<label for="name">Enter First and Last Name: </label>
<input id="name" name="name" />
<input type="button" id="addNameBtn" value="Enter Name" />
<input type="button" id="clearBtn" value="Clear Output" />
</p>
<p>
<label for="output">Output:</label><br />
<textarea cols="20" rows="15" id="output" ></textarea>
</p>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">grabText();</script>
</body>
</html>
`function grabText(){
var arr = [];
var arr2 =[];
var len = arr.length;
for (var i = 0; i<len; i++);
{
var txt = document.getElementById('name').value;
var textArea = document.getElementsByTagName('textarea');
if (txt !=="")
{
arr.push(txt);
}
}
arr2.push(arr);
arr2.sort();
var arrStr = arr2.join();
textArea[0].value = arrStr;
document.getElementById('name').value = '';
}
var btn = document.getElementById('addNameBtn');
btn.onclick = grabText;`
Playground
var textArea = document.getElementById('output');
var name = document.getElementById('name');
var btn = document.getElementById('addNameBtn');
var arr = [];
// Why whould you need arr2? to store the original?
function grabText(){
var txt = name.value;
if (txt !==""){
arr.push(txt);
}
arr.sort();
var arrStr = arr.join();
textArea.value = arrStr;
name.value = '';
}
btn.onclick = grabText;
A few things:
The for statement for (var i = 0; i<len; i++); - notice the very last character - a semi-colon. This for statement does very little - it evaluates and increments i, not the statements which follow.
var len = arr.length; syntax is correct, but the problem is arr is declared immediately before it and has a length of zero.
var arr2 stores the contents between invocations, but it has function scope and needs to be moved outside of the grabText function.

Categories

Resources