I have table that is created that shows each item added to the array. In the last row of each column is an action field that lets you either edit or delete from the row. I am not sure how I am supposed to accomplish this. What I have so far does not work properly.
function del(item) {
participantList.splice(item,1);
displayLIst();
}
function addInfo() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var email = document.getElementById("email").value;
if(fname !='' && lname !="" && email !='') {
participantList[count] = new Object();
participantList[count].Fname = fname;
participantList[count].Lname = lname;
participantList[count].Email = email;
participantList[count].Action = "<button onclick='del("+count+")'>Delete</button>" + "<button onclick='edit("+count+")'>Edit</button>";
count++;
document.getElementById("fname").value ="";
document.getElementById("lname").value = "";
document.getElementById("email").value = "";
}
displayList();
}
I want to delete every object from the specified row in the array.
How are you getting the elements and putting them into the participant list?
Do you have references to the elements? Can you include the HTML as well and all the related code to what you want to do?
Below is how I would get all of the elements, and remove one.
You can remove an element by calling .remove() on it
Here is my example code: http://jsfiddle.net/gabs00/cxt170re/
var listItems = document.querySelectorAll('li');
var item = listItems[1];
item.remove();
querySelectorAll creates a live node list
I grab one of those elements (index 1) and delete it with Element.remove();
Check out the fiddle to see it in action.
Here is a current working version:
var participantList = [];
var edit = function(item) {};
var del = function(item) {
participantList.splice(item,1);
displayList();
};
function addInfo() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var count = participantList.length;
if(fname !='' && lname !="" && email !='') {
var item = {};
item.Fname = fname;
item.Lname = lname;
item.Email = email;
item.Action = "<button onclick='del("+count+")'>Delete</button><button onclick='edit("+count+")' disabled>Edit</button>";
participantList.push(item);
document.getElementById("fname").value ="";
document.getElementById("lname").value = "";
document.getElementById("email").value = "";
}
displayList();
};
var displayList = function () {
// clean previous data
console.log(participantList);
document.getElementById("results").innerHTML = "";
var content = "";
for(var i = 0; i<participantList.length; i++) {
content += "<tr>";
content += "<td>" + participantList[i].Fname + "</td>";
content += "<td>" + participantList[i].Lname + "</td>";
content += "<td>" + participantList[i].Email + "</td>";
content += "<td>" + participantList[i].Action + "</td>";
content += "</tr>"
}
document.getElementById("results").innerHTML = "<table>" + content + " </table>";
};
With the following HTML Code:
<input type="text" id="fname" />
<input type="text" id="lname" />
<input type="text" id="email" />
<button onclick="addInfo()">
Add
</button>
<div id="results">
EDIT: Missing JSFiddle link: https://jsfiddle.net/d64314uk/
Related
I have a JS function where I'm dynamically creating a set of buttons. The buttons are placed in rows such that everytime a button is clicked, that particular row needs to be added to another table below that division.
I am able to successfully add only the first row of the original table to the intended table below the check division. All the others are not working. I'm not sure why the event-listener is not being called for all the Select buttons.
Dynamically creating the Original Table
for(var q=0;q<attributesNameArray.length;q++)
{
var chkID = "chkID"+elementID+attributesNameArray[q];
var aggComboID = "Aggregate-Combo"+q;
var attrNameID = "attrName"+q;
var attrTypeID = "attrType"+q;
var btnID = q+"addSelectedColumnBtn";
chkname = attributesNameArray[q];
chkVal = attributesDataTypeArray[q];
var asNameLbl = "usr"+q;
asNameid = asNameLbl;
$("#tableSelectedAttributes").append(
"<tr>"+
"<td id='"+attrNameID+"'>"+attributesNameArray[q]+"</td>"+
"<td id='"+attrTypeID+"'>"+attributesDataTypeArray[q]+"</td>"+
"<td><input type='text' id='"+asNameid+"'></td>"+
"<td>"+
"<select id='"+aggComboID+"' name='Aggregate-Combo' class='form-control'>"+
"<option value='Select an option'>Select an option</option>"+
"<option value='MIN'>MIN</option>"+
"<option value='MAX'>MAX</option>"+
"<option value='SUM'>SUM</option>"+
"<option value='AVG'>AVG</option>"+
"<option value='COUNT'>COUNT</option>"+
"</select>"+
"</td>"+
"<td><button id='addSelectedColumnBtn' name='"+btnID+"' class='btn btn-info'>Select</button></td>"+
"</tr>"+
"</div>"
);
}
...
document.getElementById("addSelectedColumnBtn").addEventListener("click", function() {
displaySelectedColumns(this,fromNameSt);
}, false);
displaySelectedColumns(this,fromNameSt)
function displaySelectedColumns(sender,fromNameSt)
{
var clickedelemId=sender.name;
q = clickedelemId.charAt(0);
var aggComboID = "Aggregate-Combo"+q;
var attrNameID = "attrName"+q;
var attrTypeID = "attrType"+q;
var asNameLbl = "usr"+q;
var selTableId1 = "sel1"+selectedColumnCount;
var selTableId2 = "sel2"+selectedColumnCount;
var selTableId3 = "sel3"+selectedColumnCount;
var selTableId4 = "sel4"+selectedColumnCount;
var attributeName = document.getElementById(attrNameID).innerText;
var attributeType = document.getElementById(attrTypeID).innerHTML;
var selectedAsName = document.getElementById(asNameLbl).value;
var choice=document.getElementById(aggComboID);
var selectedAggregate = choice.options[choice.selectedIndex].text;
alert(attributeName+" "+attributeType+" "+selectedAsName+" "+selectedAggregate);
if(selectedAggregate == "Select an option")
{
if(selectedAsName == "" || selectedAsName == " " || selectedAsName == "null" || selectedAsName == "undefined" ||selectedAsName == null || selectedAsName == undefined)
{
alert("As name: false");
$("#displaySelectedColumnTable").append(
"<tr>"+
"<td id='"+selTableId1+"'>"+attributeName+"</td>"+
"<td id='"+selTableId2+"'>"+attributeType+"</td>"+
"<td id='"+selTableId3+"'></td>"+
"<td id='"+selTableId4+"'></td>"+
"</tr>"
);
}
else
{
$("#displaySelectedColumnTable").append(
...
Any suggestions in this regard will be highly appreciated.
Id's have to be unique across your html page, addSelectedColumnBtn is repeated for every button.
Make it a unique id first by appending the same q variable which you added for the select element
"<td><button id='addSelectedColumnBtn_" + q + "' name='"+btnID+"' class='btn btn-info'>Select</button></td>"+
Now call this addEventListener inside the for-loop only for all buttons
document.getElementById("addSelectedColumnBtn_" + q).addEventListener("click", function() {
displaySelectedColumns(this,fromNameSt);
}, false);
I am working on Address book using HTML,CSS and Javascript. First I am reading some data entries from a JSON file. Then storing those entries into local storage. Then I am taking input from the user in few input fields through the function called addToBook(). And then storing all the data in JSON format in the variable called addressBook. But when i am trying to print this data in the function called showaddressBook(). It is not happening as it is showing as Undefined in the chrome console. Refer to this line(console.log(addressBook[i].practice_name);) in the function showaddressBook(). Any idea guys. Thanks in advance.
window.onload = function(){
var quickAddFormDiv = document.querySelector('.quickaddForm');
var AddBtn = document.getElementById('Add');
// Form Fields
var lastname = document.getElementById('lastname');
var firstname = document.getElementById('firstname');
var email = document.getElementById('email');
var specialty = document.getElementById('specialty');
var practicename = document.getElementById('practicename');
// Divs etc.
var addBookDiv = document.querySelector('.addbook');
var addressBook = [];
var people;
localStorage.clear();
//--------------------------------------------------------------------
//To display the contents of JSON file
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
people = response.people;
//var output = "";
var str1 = '';
for(var i = 0; i <people.length;i++){
str1 += '<div id="entry">';
str1 += '<div id="name"><p>' + people[i].last_name +', '+people[i].first_name+ '</p></div>';
str1 += '<div id="email"><p>' + people[i].email_address + '</p></div>';
str1 += '<div id="practicename"><p>' + people[i].practice_name + '</p></div>';
str1 += '<div id="specialty"><p>' + people[i].specialty + '</p></div>';
str1 += '<div id="del">Delete</div>';
}
for(var i = 0; i < people.length;i++){
var obj = new jsonStructure(people[i].last_name,people[i].first_name,people[i].email_address,people[i].specialty,people[i].practice_name);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
}
document.getElementsByClassName("addbook")[0].innerHTML = str1;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
//------------------------------------------------------------------------------
AddBtn.addEventListener("click", addToBook);
//var addressBook = [];
addBookDiv.addEventListener("click", removeEntry);
function jsonStructure(lastname,firstname,email,specialty,practicename){
this.lastname = lastname;
this.lastname += ", "+firstname;
this.email = email;
this.specialty = specialty;
this.practicename = practicename;
}
function addToBook(){
var isNull = lastname.value!='' && firstname.value!='' && email.value!='' && specialty.value!='' && practicename.value!='';
if(isNull){
// format the input into a valid JSON structure
var obj = new jsonStructure(lastname.value,firstname.value,email.value,specialty.value,practicename.value);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
console.log(localStorage['addbook']);
clearForm();
showaddressBook();
}
}
function removeEntry(e){
// Remove an entry from the addressBook
if(e.target.classList.contains('delbutton')){
var remID = e.target.getAttribute('data-id');
addressBook.splice(remID,1);
localStorage['addbook'] = JSON.stringify(addressBook);
showaddressBook();
}
}
function clearForm(){
var formFields = document.querySelectorAll('.formFields');
for(var i in formFields){
formFields[i].value = '';
}
}
function showaddressBook(){
if(localStorage['addbook'] === undefined){
localStorage['addbook'] = '';
} else {
addressBook = JSON.parse(localStorage['addbook']);
addBookDiv.innerHTML = '';
var str = '';
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].last_name +', '+addressBook[i].first_name+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email_address + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practice_name + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practice_name);
}
}
}
showaddressBook();
}
There are typo mistakes,
practice_name should be practicename
last_name should be lastname
first_name should be firstname
email_address should be email
Try:
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].lastname +', '+addressBook[i].firstname+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practicename + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practicename);
}
I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>
I've added a sample Javascript array in my web. Funny that it works in jsfiddle but unfortunately not working in Eclipse JSP. Here's the code.
Javascript:
var titles = [];
var names = [];
var tickets = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert() {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
jsfiddle link
You should wait for the page to finish loading all its elements.
You can either do:
window.onload=function(){
// Do stuff here
};
Or if you are using jQuery:
jQuery(document).ready(function(){
// Do stuff here
});
I'm going to try to describe this the best I can. I have a form that the user fills out, when it confirms the users info, it then prints it out on a table, and the user may edit it directly on the table using the contendEditable attribute. The problem i'm having is if the user edits his/her email address, the browser detects it as an email address (since it's not in an input element) and doesn't pass the email through the form. All other values go through fine. I'm using PHP to process the form and just print out the fields to make sure it goes through properly.
The confirm page should like this:
John,Smith,JSMITH,abc#123.com,111-222-3345
But it looks like this:
John,Smith,JSMITH,null,111-222-3345
Any suggestions?
It would be easier if i posted my code so here it is:
HTML:
<html>
<head>
<script type = "text/javascript" src = "ext.js"></script>
</head>
<body>
<form name = "setupForm" id = "setupForm" action = "confirmSetup.php" method = "post">
<div id = "confirmInfo"></div>
<div id = "hiddenFields"></div>
</form>
</body>
</html>
/* I didn't put my full code on here as it is way too long.
But this HTML document is what is shown after input fields
have been previously submit, and this page is just to confirm
the user input.
*/
JS:
function verifyInfo(){ // This function is called when user submits all his info
var firstname = document.getElementById("txtFirstname").value;
var lastname = document.getElementById("txtLastname").value;
var username = document.getElementById("hdnUsername").value;
var email = document.getElementById("txtEmail").value;
var phone = document.getElementById("txtPhone").value;
var output = "";
output += "<table id = 'confirm'>";
output += "<tr>";
output += " <th>Firstname</th>";
output += " <td id = 'tdFirstname'>";
output += " <div onkeyup = 'updateUsername()' contentEditable>" + firstname + "</div>";
output += " </td>";
output += "</tr>";
output += "<tr>";
output += " <th>Lastname</th>";
output += " <td id = 'tdLastname'>";
output += " <div onkeyup = 'updateUsername()' contentEditable>" + lastname + "</div>";
output += " </td>";
output += "</tr>";
output += "<tr>";
output += " <th>Username</th>";
output += " <td id = 'tdUsername'>" + username + "</td>";
output += "</tr>";
output += "<tr>";
output += " <th>Email</th>";
output += " <td id = 'tdEmail'>";
output += " <div style = 'min-width:1px;' onkeyup = 'verifyEmail(this.parentNode.id,event)' contentEditable>" + email + "</div>";
output += " <div id = 'validInvalid'>";
output += " <span class = 'dgreen'><br/>Valid email!</span>";
output += " </div>";
output += " </td>";
output += "</tr>";
output += "<tr>";
output += " <th>Phone</th>";
output += " <td id = 'tdPhone'>";
output += " <div style = 'min-width:1px;' onkeyup = 'verifyPhone(this.parentNode.id,event)' contentEditable>" + phone + "</div>";
output += " <div id = 'validInvalid1'>";
output += " <span class = 'dgreen'><br/>Valid phone!</span>";
output += " </div>";
output += " </td>";
output += "</tr>";
output += "</table>";
output += "<input type = 'button' name = 'submitSetup' id = 'submitSetup' value = 'Get Set Up!' onclick = 'goToConfirm()'/>";
document.getElementById("confirmInfo").innerHTML = output;
}
/* The way that function works is it takes the inputted text,
and places it into the table. This table enables the user to dynamically make any
changes necessary right onto the table. The username is created from first initial
and last name, which is called on the 'updateUsername()' function, which I am leaving
out.
*/
function verifyEmail(id,e){
var unicode = e.charCode ? e.charCode : e.keyCode;
if((unicode < 37 || unicode > 40) && unicode != 9){ // This doesn't allow email to be verified if the arrow keys, or tab key is pressed
var email = document.getElementById(id).firstChild.firstChild.nodeValue;
var emailFilter = /^[^0-9][A-z0-9_]+([.]A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/;
if(!emailFilter.test(email)){ // Checks if valid email
document.getElementById("validInvalid").innerHTML = "<span class = 'red'><br/>Not a valid email!</span>";
}else{
document.getElementById("validInvalid").innerHTML = "<span class = 'dgree'><br/>Valid email!</span>";
}
}
disableButton(); //If email or phone is invalid, button will be disabled
}
function verifyPhone(id,e){
var unicode = e.charCode ? e.charCode : e.keycode;
if((unicode < 37 || unicode > 40) && unicode != 9)){
var phone = document.getElementById(id).firstChild.firstChild.nodeValue;
if(phone.length > 12){ // Doesn't let user put it more than 12 characters (xxx-xxx-xxxx)
var difference = phone.length - 12;
phone = phone.substr(0,phone.length - difference);
document.getElementById(id).firstChild.firstChild.nodeValue = phone;
}
var phoneFilter = /\d{3}\-\d{3}\-\d{4}/;
if(!phoneFilter.test(phone)){ // Checks for valid phone number
document.getElementById("validInvalid1").innerHTML = "<span class = 'red'><br/>Not a valid phone!</span>";
}else{
document.getElementById("validInvalid1").innerHTML = "<span class = 'dgreen'><br/>Valid phone!</span>";
}
}
disableButton();
}
function disableButton(){
var email = document.getElementById("tdEmail").firstChild.nextSibling.firstChild.className;
var phone = document.getElementById("tdPhone").firstChild.nextSibling.firstsChild.className;
if(email == "red" || phone == "red"){
document.getElementById("submitSetup").disabled = true;
}else{
document.getElementById("submitSetup").disabled = false;
}
}
function goToConfirm(){ //This is the function that goes to confirmsetup.php. it works fine if email isn't edited in table, but if email is edited, it doesn't work
var firstname = document.getElementById("tdFirstname").firstChild.firstChild.nodeValue;
var lastname = document.getElementById("tdLastname").firstChild.firstChild.nodeValue;
var username = document.getElementById("tdUsername").firstChild.nodeValue;
var email = document.getElementById("tdEmail").firstChild.firstChild.nodeValue;
var phone = document.getElementById("tdPhone").firstChild.firstChild.nodeValue;
var hiddenfields = document.getElementById("hiddenFields");
var input = "<input type = 'hidden' name = 'hdnFirstname' id = 'hdnFirstname' value = '"+firstname+"'/>";
input += "<input type = 'hidden' name = 'hdnLastname' id = 'hdnLastname' value = '"+lastname+"'/>";
input += "<input type = 'hidden' name = 'hdnUsername' id = 'hdnUsername' value = '"+username+"'/>";
input += "<input type = 'hidden' name = 'hdnEmail' id = 'hdnEmail' value = '"+email+"'/>";
input += "<input type = 'hidden' name = 'hdnPHone' id = 'hdnPhone' value = '"+phone+"'/>";
hiddenFields.innerHTML = input;
document.setupForm.submit();
}
/* That is the end of my javascript file, it's a lot,
but hopefully you can understand it
*/
Finally, the final php script is simple:
<?php
$fn = $_POST['hdnFirstname'];
$ln = $_POST['hdnLastname'];
$un = $_POST['hdnUsername'];
$em = $_POST['hdnEmail'];
$ph = $_POST['hdnPhone'];
die($fn.",".$ln.",".$un.",".$em.",".$ph);
?>
the firstname, lastname, username, and phone alway print out correctly.
When the email is not edited, it prints out correctly,
When the email is edited, it prints out as null.
This is incorrect, values are parsed as text. Please review the code and make sure that you parse correct form names from http request object. It should fix your issue.