array.length do not increment on push() - javascript

I push strings to an array and display the elements in a textarea. The array populates as expected when onchange is triggered, and then I need to get the number of elements in the array, but the IDarr.length stays fixed on 2. Can anybody advise me on the error? Here’s my code:
Script:
function UpdBttn(ct){
var array = document.getElementById('array').innerHTML;
var IDarr = [array];
IDarr.push(ct);
document.getElementById('array').innerHTML = IDarr;
alert(IDarr.length);
}
Receiving textarea:
<textarea id="array"></textarea><br>
Input text (from databaseloop) to populate IDarr onchange:
<input Type="text" id="event<%=ct%>" value="<%=events(dates)%>" onchange="UpdBttn(this, '<%=ct%>')">

I'm not exactly sure what you're trying to achieve, but you might do something like this:
function UpdBttn(ct){
var array = document.getElementById('array').innerHTML;
var IDarr = array.split(',');
IDarr.push(ct);
document.getElementById('array').innerHTML = IDarr.join(',');
alert(IDarr.length);
}

You need to define your variable outside of the function to prevent it from initializing each time you call the function try this:
var IDarr = [];
function UpdBttn(ct){
var array = document.getElementById('array').innerHTML;
IDarr.push(ct);
document.getElementById('array').innerHTML = IDarr;
alert(IDarr.length);
}

innerHTML returns a string. So when you retrieve array using var array = document.getElementById('array').innerHTML; it is single string. So you have one element that is string in your array and after pushing another element it become two.
const button = document.querySelector('button');
button.addEventListener('click', function() {
const divContent = document.querySelector('#array').innerHTML
const idArr = [divContent];
console.log(idArr);
idArr.push('lorem');
document.getElementById('array').innerHTML = idArr;
// The length will be same
console.log(idArr.length);
});
<div id="array">Item1, Item2</div>
<button>Click Me</button>
I am not really sure about how your innerHTML (Note - If you need only the contents between tag, better use textContent) looks. But you need to convert your textContent from string to array.
const button = document.querySelector('button');
button.addEventListener('click', function() {
const divContent = document.querySelector('#array').innerHTML
const idArr = [...divContent.split(',')];
console.log(idArr);
idArr.push('lorem');
document.getElementById('array').innerHTML = idArr;
console.log(idArr.length);
});
<div id="array">Item1,Item2</div>
<button>Click Me</button>

This implementation is wrong. when use create var IDarr = [array];
you always create a new array with one element. So when you push output array is same 2 for all the time. If you trying to implement the char counter functionality. Please user string, not an array.
Wrong:
var arr = ['s']
console.log(arr.length) // 1
console.log(arr) //s
arr.push('e')
console.log(arr.length) // 2
console.log(arr) //se
//next time
var arr = ['se']
console.log(arr.length) // 1
console.log(arr) //se
arr.push('e')
console.log(arr.length) // 2
console.log(arr) //se,e
Correct Way:
var text = 's'
console.log(text.length) // 1
console.log(text) //s
text = text + 'e'
console.log(text.length) // 2
console.log(text) //se
//next time
var text = 'se'
console.log(text.length) // 2
console.log(text) //se
text = text + 'ee'
console.log(text.length) // 3
console.log(text) //see

Related

Array not giving expected answer using split function

In this code console.log (name[i]) results in first character of split string(i.e. c ,s,t) but i want name separate like chris. and its giving the expected result on MDN but not on console on js.
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
var name=new Array();
for(var i=0;i<char.length;++i){
name=char[i].split(':');
console.log(name[i]);
}
Your code should look like
var char=['chris:2255655','sarrah:5456454','taur:5655226'];
for(var i=0;i<char.length;++i){
var w = char[i].split(":");
console.log(w[0]);
}
Please check my snippet. It seems that your split was not resulting an array but a string. So you were getting only the first symbol
You can simply do:
var char=['chris:2255655','sarrah:5456454','taur:5655226']
// As array
console.log(char.map(x => x.split(':')[0]))
// As a string
console.log(...char.map(x => x.split(':')[0]))
We are using map to go through each of the strings and split on :.
Since split gives us an array we take the 0 index which contains the name. Since Map returns an array you can either leave as is or destructure it with ... to get its contents.
You can do like this.
const char=['chris:2255655','sarrah:5456454','taur:5655226'];
const name= [];
for(let i=0;i<char.length;i++){
let val =char[i].split(':');
name.push(val[0]);
console.log(name[i]);
}
Since you know the position of your selection you can assign directly to a variable:
var char = ['chris:2255655', 'sarrah:5456454', 'taur:5655226']
var names = char.map(item => {
var [name] = item.split(':'); // <- select only first index
// var [name, id] = item.split(':'); // <- select first and second index
// var [name, ...rest] = item.split(':'); // <- select first and rest of the elements
// var [name,] = item.split(':'); // <- select first and skip next element index using ","
return name;
})
console.log(names);

How to check an input words against several arrays in Javascript

I need to test all the words entered into an input against 3 objects and determine which array they belong to so I can output a URL to an API.
I want to achieve this with Javascript/jQuery.
For example if the input had these words: keyword1 keyword2 keyword3 keyword5
All keyword entries will be added from a autocomplete plugin.
I then need to test them against 3 arrays.
var array1 = ["keyword2", "keyword6"];
var array2 = ["keyword3", "keyword4"];
var array3 = ["keyword1", "keyword5"];
I need to determine what array they came from so I can output a URL and add the values to specific keys in a URL.
Example:
domain.com/api?array1= [insert keyword(s)] &array2= [insert keyword(s)] &array3= [insert keyword(s)]
The keywords need to be sent as an array and must have spaces replaced with dashes.
I am using jQuery to perform a GET request with the URL generated.
You can make the code shorter by creating an array of arrays but this works
var input = "keyword1 keyword2 keyword3 keyword5".split(" ");
var array1 = ["keyword2", "keyword6"];
var array2 = ["keyword3", "keyword4"];
var array3 = ["keyword1", "keyword5"];
var arr1=[],arr2=[],arr3=[];
$.each(input,function(_,keyword) {
if ($.inArray(keyword,array1) !=-1) arr1.push(keyword);
if ($.inArray(keyword,array2) !=-1) arr2.push(keyword);
if ($.inArray(keyword,array3) !=-1) arr3.push(keyword);
});
var url = "domain.com/api/?",keywords="";
if (arr1.length>0) keywords += "&array1="+arr1.join(",");
if (arr2.length>0) keywords += "&array2="+arr2.join(",");
if (arr3.length>0) keywords += "&array3="+arr3.join(",");
if (keywords.length>0) url += keywords.substring(1).replace(/ /g,"-");
console.log(url)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can put all the array objects into a parent array and then loop it
var parentArray = [
["keyword2", "keyword6"],
["keyword3", "keyword4"],
["keyword1", "keyword5"]
]
$.each(parentArray,function(key,value){
//here you can check
$.each(value,function(key1,value1){
if('your key word') == value1{
// then the array you are looking for would be "key" of that particular loop
}
});
});
EDIT: Now, this should definitely work
Here's a vanilla JS version:
var words = 'keyword1 keyword2 keyword3 keyword5';
// first create an object that contains your arrays
var dict = {
array1: ["keyword2", "keyword6"],
array2: ["keyword3", "keyword4"],
array3: ["keyword1", "keyword5"]
}
// start building up a new object that mirrors the existing one
// but that only contains those keywords that are in the input string
function buildURLObj(dict, words) {
var out = {};
// split the keywords string into an array
words = words.split(' ');
// loop over the object
for (var p in dict) {
out[p] = [];
// loop over the array of keywords
for (var i = 0, l = words.length; i < l; i++) {
// if the keyword in the array, push it to the
// temporary object
if (dict[p].indexOf(words[i]) > -1) {
out[p].push(words[i]);
}
}
}
// return the completed URL using createURL
return createURL(out);
}
// create a URL from the new object
function createURL(arr) {
var url = [];
for (var p in arr) {
// if the array is not empty, don't add it to the completed URL
// otherwise start building up the URL string
if [arr[p].length) {
var subURL = [];
subURL.push(p);
subURL.push('[' + arr[p].join('-') + ']');
url.push(subURL.join('='));
}
}
// return the completed URL
return url.join('&');
}
// "array1=[keyword2]&array2=[keyword3]&array3=[keyword1-keyword5]"
buildURL(dict, words);
DEMO

How to get the ID of a dynamic element when loaded?

VIEW
$1 = array('value'=>'1|3','class'=>'temp_stok', 'id'=>'st1');
$2 = array('value'=>'2','class'=>'temp_stok','id'=>'st2');
$3 = array('value'=>'5|7','class'=>'temp_stok','id'=>'st3');
echo form_input($1);echo form_input($2); echo form_input($3);
i want to split every value content '|'
var id = $('.temp_stok').id();
var val_id = $('#st'+id).val();
if(val_id.indexOf('|') >= 1)
{ var _stok = val_id.split('|');
var stok1 = _stok[0]; var stok1 = _stok[1]; }
but the problem is get the id. How can i get id ?
You may try something like this (Example):
// Select all inputs that contains | in it's value
var inputsWithPipe = $("input[value*='|']");
// Then loop all the inputs and split
$.each(inputsWithPipe, function(k, v){
var arr = v.value.split('|');
console.log(arr); // an array of numbers
});
Now you may use each arr array as you want.
Try this to get the id of the element you are interested in:
var id = $('.temp_stok').attr('id');

jquery get the unreapeatable values

i have a array with numbers. i need that array value to be generated once i click on the button, while i click on the button i need to get the value random wise from the array, but the value should not be repeated.
ex, if i get a 2 from out of 5, then i should not get the 2 again. for this i wrote this function, but the values are repeating... any idea?
var ar = [0,1,2,3,4,5];
var ran = Math.floor(Math.random()*ar.length);
ar.splice(ran,1);
alert(ar.splice);
the array values should not be removed. because if i click the button again, i need to get the values like before.
i did my work like this : but the rand values are repeating, any one can correct this to get unrepeatable values to get?
$(document).ready(function(){
var myArray = [1,2,3,4,5];
var mySize = 5;
x = 0;
while(mySize>=1){
var rand = Math.floor(Math.random()*mySize);
mySize--;
alert(rand);
}
})
You need your array to be in an outer scope for this like:
(function(){
var ar = [0,1,2,3,4,5];
document.getElementById('thebutton').onclick = function(){
alert(ar.splice(Math.floor(Math.random()*ar.length), 1));
};
})();
JSFiddle Example
If you create your array inside the onclick function then you are just recreating the entire array every time the button is clicked.
Take a look at this demo. In this it randomizes the array values and will repeat only after all the values are utilized.
Demo
Based on the update in your question here it is take a look.
http://jsfiddle.net/MbkwK/2/
var ar = [0, 1, 2, 3, 4, 5];
document.getElementById('thebutton').onclick = function() {
var shuffle = [];
var copyarr = ar.slice(0);
var arlength = copyarr.length;
for (i = 0; i < arlength; i++) {
shuffle.push(copyarr.splice(Math.floor(Math.random() * copyarr.length), 1));
}
alert(shuffle.join(","));
};
Working demo - http://jsfiddle.net/ipr101/qLSud/1/

Javascript dynamic array of strings

Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Code is appreciated.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
First is the prompt() function which displays a popup asking the user for some input.
Pros: easy. Cons: ugly, can't go back to edit easily.
Second is using html <input type="text"> fields.
Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.
For the prompt method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
Put a single input field on the page.
Add an onfocus handler to it.
Check if there is another input element after this one, and if there is, check if it's empty.
If there is, don't do anything.
Otherwise, create a new input, put it after this one and apply the same handler to the new input.
When the user clicks OK, loop through all the <input>s on the page and store them into an array.
eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
var junk=new Array();
junk.push('This is a string.');
Et cetera.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
Printing Order
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
Page Submission
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.
<script type="text/javascript">
var arr = [];
function add() {
var inp = document.getElementById('num');
arr.push(inp.value);
inp.value = '';
}
function show() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var con = document.getElementById('container');
con.innerHTML = html;
}
</script>
<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Categories

Resources