I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW
Related
I am working on a attendance module and this is the prototype of the code, but I have some errors.
As you can see there are dynamically generated buttons and they change colour on click event. I am also storing the value of the buttons in textboxes on click as I have to handle this data on backend with PhP, the error is that when I turn a button to green it's value goes into a textbox and when again i turn it red same value goes into another textbox also, which I don't want. So please help me in solving this problem by reducing the duplicacy of data or by providing a code of a different submit button which when clicked checks the color of all the buttons and stores the values in different textboxes respectively, one for red and one for green. Thanks in advance.
<html>
<head>
<title>Button click event</title>
</head>
<body>
<?php
for($i=0;$i<=10;$i++) {
?>
<button class="btnColorChange" id="<?php echo $i; ?>" style="background-color:#FF0000"><?php echo $i; ?></button>
<?php
}
?>
<div>
<input type="text" name="text1" id="textbox1" value=""/><br><br>
<input type="text" name="text2" id="textbox2" value=""/><br><br>
</div>
<script>
$(".btnColorChange").click(function(){
xyz = this.id
if(this.clicked){
$(this).css('background-color', '#FF0000');
const tb=document.querySelector("#textbox1");
tb.value=tb.value+","+xyz;
console.log(xyz)
this.clicked = false;
} else {
$(this).css('background-color', '#008000');
const tb2=document.querySelector("#textbox2");
tb2.value=tb2.value+","+xyz;
console.log(xyz)
this.clicked = true;
}
});
</script>
</body>
</html>
First, the below statement is wrong:
there are dynamically generated buttons...
When talking about "dynamic" elements, we talk about element that were not existing on page load. It's not the case here, since they were created before page load, on the server-side. Using a loop does not make them "dynamic".
To store clicked/unclicked ids, I suggest you to use some arrays for this.
As I understand it, you want all the "clicked" and "unclicked" ids separately.
The "never clicked" are ignored.
Using two arrays, you can store ids in the relevant group... And even sort them (optionnally).
And you can send those arrays straight to your backend... So the input elements would now be just for testing purposes.
See comments in code:
// Arrays to store ids
var clicked = [],
unclicked = [];
$(".btnColorChange").on("click",function(){
// useful for this demo
console.clear();
// Get the clicked element id
var this_id = this.id;
console.log("Clicked id: "+this_id);
// Toggle the classes (button colors)
$(this).toggleClass("clicked unclicked");
// Check if in array
var in_clicked = $.inArray(this_id,clicked);
var in_unclicked = $.inArray(this_id,unclicked);
//console.log(in_clicked+" "+in_unclicked)
// If clicked
if($(this).hasClass("clicked")){
if(in_clicked==-1){
clicked.push(this_id);
clicked.sort();
}
if(in_unclicked>-1){
unclicked.splice(in_unclicked,1);
}
}
// If unclicked
if($(this).hasClass("unclicked")){
if(in_unclicked==-1){
unclicked.push(this_id);
unclicked.sort();
}
if(in_clicked>-1){
clicked.splice(in_clicked,1);
}
}
// Show arrays content in console
console.log(clicked);
console.log(unclicked);
// Show the ids in inputs as a coma separated string
$("#textbox1").val(clicked.join(","));
$("#textbox2").val(unclicked.join(","));
});
.unclicked{
background-color: #FF0000;
}
.clicked{
background-color: #008000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btnColorChange unclicked" id="1">1</button>
<button class="btnColorChange unclicked" id="2">2</button>
<button class="btnColorChange unclicked" id="3">3</button>
<button class="btnColorChange unclicked" id="4">4</button>
<button class="btnColorChange unclicked" id="5">5</button>
<br>
<br>
<div>
<input type="text" name="text1" id="textbox1" value=""/><br><br>
<input type="text" name="text2" id="textbox2" value=""/><br><br>
</div>
Please run the snippet in full page mode, because of the console logs.
For more reading, the below demo uses the following methods:
.on()
.toggleClass()
$.inArray()
.hasClass()
.push()
.sort()
.splice
.val()
.join()
You certainly noticed that I used two CSS rules for the button colors, instead of inline style attributes.
CodePen
If i understood you well, you want for example the Button to handle updates of textbox1 on first click and update textbox2 on second click. You could do this.
$(".btnColorChange").on("click", function(){
var btn = $(this);
var id = btn.attr("id");
if(btn.hasClass('clicked')){
var textboxselected = $("#textbox1");
var backgroundColor = "#FF0000";
btn.removeClass('clicked');
}else{
var textboxselected = $("#textbox2");
var backgroundColor = "#008000";
btn.addClass('clicked');
}
btn.css("background-color", backgroundColor);
textboxselected.val(textboxselected.val()+id);
});
Suppose you want to update same textbox
$(".btnColorChange").on("click", function(){
var btn = $(this);
var id = btn.attr("id");
var textvalue = $("#textbox1").val();
if(btn.hasClass('clicked')){
var backgroundColor = "#FF0000";
btn.removeClass('clicked');
}else{
var backgroundColor = "#008000";
btn.addClass('clicked');
}
btn.css("background-color", backgroundColor);
$("#textbox1").val(textvalue);
});
Its untested but hopes it works for you.
So, I was adding a delete all button and it works, the only problem is that it needs to be double clicked just to make it work.
may I ask what's wrong? thank you :)
I added the codes that were used to create the button here:
<body>
<!--for everything in the navigation part including the add favorite bar-->
<div class="topnav">
<div class="addFave">
<!--the text bar-->
<input type="text" name="enter" class="enter" value="" id="added" placeholder= "Add Favorites"/>
<!--the enter button-->
<input type="button" value="Enter" id = "addIt" OnClick="adding()" />
<!--for the script of the add favorite bar to add its functions-->
<script type="text/javascript">
var faves = [];
var y = document.getElementById("added");
function adding() {
faves.push(y.value);
document.getElementById("faveLists").innerHTML = faves;
}
var input = document.getElementById("added");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("addIt").click();
}
});
</script>
</div>
</div>
<br />
<div class="buttons">
<button onclick="eradicateFaves()">Remove All Favorite</button>
<script>
-coding to remove all the favorites on the list-->
function eradicateFaves(){
document.getElementById("faveLists").innerHTML = faves;
while(faves.length > 0){
faves.shift();
}
}
</script>
</div>
<p id = "faveLists"></p>
while(faves.length > 0){
faves.shift();
}
Why not just faves = [] to empty it? And shouldn't you empty the list before assigning it? That's why you need two clicks; first time re-assigns current list then empties it, and second time assigns the empty list then does nothing more as it is already empty. So, try this:
function eradicateFaves(){
faves = [];
document.getElementById("faveLists").innerHTML = faves;
}
When you say "delete all" I assume you mean reset the faves array back to []. Well why not just do this:
function eradicateFaves() {
faces = [];
document.getElementById("faveLists").innerHTML = faves;
}
The reason it wasn't working earlier was because Array.prototype.shift() only removes the first element of the array. According to the MDN docs:
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;
I am trying to add elements to an array via a form. I am using the unshift() method. The code below doesn't work and I would like to know why.
<form>
<input id="input"> </input>
<input type = "button" id="button"> Click me </input>
</form>
<script>
var input = document.getElementById("input").value;
var button = document.getElementById("button");
var myArray = [];
myArray.unshift(input);
button.onclick = function alerted (){
alert(myArray);
};
</script>
Your quoted code runs immediately when the page is loaded. The form field won't have anything in it then, so its value will be ''. When you alert that, the default toString operation on the array will result in '' and the alert will be blank.
You want to run your unshift code in response to a user event, such as the button being clicked, rather than right away. You can do that by setting input to be the element (remove .value from that line) and then moving your line with unshift into the function you're assigning to onclick, adding the .value there:
button.onclick = function alerted (){
myArray.unshift(input.value);
alert(myArray);
};
Other notes:
You never write </input>. Normally you don't close input tags at all. If you're writing XHTML (you probably aren't), you'd put the / within the main input tag like this: <input id="input" />. But again, you're probably not writing XHTML, just HTML.
The value (caption) of an input button goes in its value attribute, not content within opening and closing tags. (You would use opening and closing tags with the button element, not input.)
Taking all of that together, here's a minimalist update: Live copy | source
<form>
<input id="input"><!-- No ending tag -->
<input type = "button" id="button" value="Click me"><!-- No ending tag, move value where it should be -->
</form>
<script>
var input = document.getElementById("input"); // No .value here
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // Moved this line, added the .value
alert(myArray);
};
</script>
DEMO
You need to a) get the value in the click and b) return false if you want the button to not submit. I changed to button. Alternative is <input type="button" value="click me" id="button" />
You may even want to empty and focus the field on click...
<form>
<input id="input" type="text"/>
<button id="button"> Click me </button>
</form>
<script>
var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(input.value); // get the value
alert(myArray);
return false;
};
</script>
You're not getting the new value in the onclick function.
Try this: http://jsfiddle.net/SeqWN/4/
var button = document.getElementById("button");
var i = document.getElementById("input");
var myArray = [];
button.onclick = function alerted (){
myArray.unshift(i.value);
alert(myArray);
};
I am brand new in WebDevelopment and I came across the following issue.
I have an html file where a textbox is defined as well as a "View all Contents" button
The user can enter a value in the textbox and submit the data
Then repeat this action multiple times
Every time a new value is entered this value should be stored to a
Javascript array
The user will be able to view the contents of the Javascript array
when clicking on the button "View all Contents".
So my problem is how these values are stored dynamically in Javascript and printed when the user is finished.
Your answer is very much appreciated.
Best Regards
Olga
A very trivial example: http://jsfiddle.net/pimvdb/unEMp/.
<input type="text" id="textbox">
<br>
<input type="button" id="add" value="Add">
<br>
<input type="button" id="view" value="View all Contents">
with:
var arr = []; // the array
document.getElementById('add').onclick = function() {
arr.push(document.getElementById('textbox').value); // add textbox value to array
document.getElementById('textbox').value = ''; // clear textbox value
};
document.getElementById('view').onclick = function() {
alert(arr.join(', ')); // alert array contents as a string; elements are delimited by ', '
};
First you'll want to create your array in the global scope - this means outside of a method body, somewhere in the <script></script> body:
var myArray = new Array();
Next, you'll want to append the array with a new value each time the user clicks a button:
function myButtonClick(){
var myTb = document.getElementById("textBox1");
myArray.push(myTb.value);
myTb.value = ""; // reset the textbox
}
Next, you'll want another button handler for the click on "View All":
function myViewAllButtonClick(){
// will create a string of myArray's values, seperated by new line character
var msg = myArray.join("\n");
// will show the user all of the values in a modal alert
alert(msg);
}
Your HTML might look like:
<input type="text" id="textBox1" />
<input type="button" id="button1" value="Add Value" onclick="myButtonClick();"/>
<input type="button" id="button2" value="Show All" onclick="myViewAllButtonClick();"/>
When you get the hang of things, you can get rid of the "Add Value" button all together and use:
<input type="text" id="textBox1" onchange="onTextChanged(this)"/>
With a handler like:
function onTextChanged(e){
if(e.value == "") return;
myArray.push(e.value);
e.value = "";
}
The onTextChanged handler will fire when the user changes text in the textbox (it won't fire though until the textbox loses focus, which may make it bad for this example, but still a good JS skill to learn/understand).
Happy coding - good luck!
B
JavaScript array could be dynamicaly changed:
var array = [];
function foo() {
array.push('foo');
}
function boo() {
array.push('boo');
}
i put together a small example: http://jsbin.com/izumeb/3
<p><input type="text" id="txt"></input><button onclick="addToAll();">add to selection</button></p>
<p><button onclick="showAll();">show all</button></p>
<p id="all"></p>
and JS
<script>
var values = [];
function addToAll() {
var txt = document.getElementById("txt");
values.push(txt.value);
txt.value = "";
}
function showAll() {
var all = document.getElementById("all");
var str = "";
for (var i=0;i<values.length;++i) {
str += values[i] + "<br/>";
}
all.innerHTML = str;
}
</script>