Demo of Adding and removing elements by user and displaying

Read How Users can add elements to an array & than display all elements.

In above tutorial we will add another function to delete any element by user. Our function will collect key number by using indexOf method and then remove the element by using splice function. Here is the code for our function.
function remove_element(index_no){
var t1=data.splice(index_no,1);
disp(); // displaying the array elements
}
Demo is here


Here is the code
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo of adding element to an array</title>
</head>

<body>
 <script type="text/javascript">
var data = new Array(); // creating array

function add_element(){
data.push(document.getElementById('t1').value); // adding element to array
document.getElementById('t1').value=''; // Making the text box blank
disp(); // displaying the array elements
}
function remove_element(index_no){
var t1=data.splice(index_no,1);
disp(); // displaying the array elements
}
function disp(){
var str='';
str = 'total number of elements in data array : ' + data.length + '<br>';
for (i=0;i<data.length;i++) 
{ 
str += i + ':'+data[i] + " <a href=# onClick='remove_element("+data.indexOf(data[i])+")'> Remove</a> " + "<br >";  // adding each element with key number to variable
} 

document.getElementById('disp').innerHTML=str; // Display the elements of the array
}
</script>

<input type=text  id='t1'><input type=button value='Add' onClick='add_element()';>
<div id=disp></div>
</body>
</html>


plus2net.com




anjel

07-03-2015

hi..
useful code.but i have a doubt what if i want to display particular element of any index and that index value is to be taken by entering values though users.
smo

13-03-2015

You can display the value by reading the key of the array. In side the function you can see one for loop is used with variable i, if i value is taken from user then the corresponding value can be displayed.
Himari Biswas

20-01-2016

thank u very much finally my problem solved
mr red

21-02-2017

how about, if the data in the arrays are on the table? what will the code format is?
smo1234

23-02-2017

You have to first collect the data from the table by using any server side script and SQL.

While displaying the data you can use the array push to insert data to the JavaScript array. Note that while using server side script you have to echo or print the client side JavaScript code to store values inside array.

Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer