Pushing info from form values to object not working - javascript

I am having trouble with getting the values of the form i have created with javascript to push into the object.
im in a project creating an addressbook and im stuck here and dont know what to do. So if anyone can help me with that!
The first part of the code is the object function I have created. And appends the contacts to li's.
The second part of the code is to create a form, and loop a form with 5 input fields.
The third and last part of the code is where I dont know what to do or how to do.
I need to get the values of the form and push is it in to the object (as arguments?) to ( contacts = []; ) but isnt working.
//Contactlist funktion
function Contact(fname, lname, address, email, phone) {
this.fname = fname;
this.lname = lname;
this.address = address;
this.email = email;
this.phone = phone;
}
//The contacts
var contacts = [];
// Appending the objects
function theContacts() {
var body = document.getElementsByTagName('body')[0],
outerUL = document.createElement('ul'),
length = contacts.length;
outerUL.className = 'contactlist';
for (var i = 0; i < length; i++) {
var cont = contacts[i],
li = document.createElement('li'),
ul = document.createElement('ul');
li.className = 'contact'; li.innerHTML = cont.fname + ' ' + cont.lname;
ul.className = 'infos';
for (var key in cont) {
var info = document.createElement('li');
info.className = key;
info.innerHTML = cont[key];
ul.appendChild(info);
}
li.appendChild(ul); outerUL.appendChild(li);
}
body.appendChild(outerUL);
}
and then I have this part...
// Calling the object
function addForms(){
var body = document.getElementsByTagName('body')[0]
var form = document.createElement("form");
var myArray = ['fnameValue', 'lnameValue', 'addressValue', 'emailValue', 'phoneValue'];
var texts = ['First Name: ', 'Last Name: ', 'Address: ', 'Email: ', 'Phone: '];
// Create a loop of 5
for(var i = 0; i < 5; i++){
var input = document.createElement('input');
var newlabel = document.createElement('label');
// newlabel.setAttribute('for', myArray[i]);
newlabel.innerHTML = texts[i];
form.appendChild(newlabel);
input.setAttribute('type','text');
input.setAttribute('id', myArray[i]);
// adds the input's to the form.
form.appendChild(input);
}
// adds the forms to the body
body.appendChild(form);
// Add Contact Button
var addContact = document.createElement('input')
addContact.setAttribute('type', 'button')
addContact.setAttribute('id', 'addContact')
addContact.setAttribute('value', 'Add Contact')
form.appendChild(addContact);
var knapp = document.getElementById('addContact');
knapp.addEventListener('click', addNewContact)
}
This is the part that i am stuck with, and well maybe i need to modify the code above too, idk..
Please help me.
function addNewContact() {
var input1 = document.getElementById('fnameValue').value;
var input2 = document.getElementById('lnameValue').value;
var input3 = document.getElementById('addressValue').value;
var input4 = document.getElementById('emailValue').value;
var input5 = document.getElementById('phoneValue').value;
contacts.push(input1, input2, input3, input4, input5);
}
document.getElementById("newButton").addEventListener("click", addForms);

I got some things sorted out, but there is still some work cut out. Anyway, I got the addNewContact() method working after attaching the event listener directly to the button:
addContact.addEventListener('click', addNewContact, false);
In the addNewContact() method I emptied the contacts array before adding any elements to it, because otherwise after the second 'addContact' button click there'll be twice as many elements in the array.
contacts.length = 0; //this empties the array
contacts.push(input1, input2, input3, input4, input5);
Alternatively, instead of doing the above, I tried directly adding a Contact object into contacts array:
contacts.push( new Contact(input1, input2, input3, input4, input5) );
Finally, like Teemu suggested I removed the infinite loop call in the addNewContact() method
After I did those things, I got theContacts() method working partly, which was called in the addNewContact() method. Fiddle

Related

Error in my task 4, it seems that .checked and .value doesn't seem to work as intended

Link to Scrimba to check on code : https://scrimba.com/scrim/czvrQJcM
Essentially what should happen is that when the details are added and the button is clicked, the data first gets saved into the object, 'student' and pushed into the array. Then the array is run and the students names are displayed on the page.
I just solve your problem. Look:
At your enrolStudent() function you set the following line:
studentList = studentList.push(student);
So, you should change it to:
studentList.push(student);
This is because the push() method returns the length of the array. So, you don't need to attribute the operation result to the array. The method already updated its own value.
Task4 after the change:
function enrolStudent()
{
let firstnameRef = document.getElementById("fname");
let lastnameRef = document.getElementById("lname");
let studentIdRef = document.getElementById("studentid");
let dateRef = document.getElementById("date");
let courseRef = document.getElementById("course");
let genderRef = document.getElementsByName("gender");
for (let i=0; i < genderRef.length; i++)
{
if (genderRef[i].checked)
{
var genderSelection = genderRef[i];
}
}
let student = new Object();
student.firstName = firstnameRef.value;
student.lastName = lastnameRef.value;
student.id = studentIdRef.value;
student.course = studentIdRef.value;
student.gender = genderSelection.value;
student.date = dateRef.value;
studentList.push(student);
var val = studentList.push(student);
studentEnrolSummaryRef.innerHTML = displayStudents(studentList);
console.log(val);
}
```

js reset the variable on change in select-option menu

i have 2 arrays of data form php and using a select-option menu to get the current key for both arrays.
When the key is chosen from a select menu, i use the key to display this key data for both arrays. If the second array doesnt have the key, it should display nothing.
It works fine when both arrays have identical keys.
But when the 2nd array doesnt have the key, it shows the previous data instead of nothing.
php array is similar to:
$arrays['first']['*random_keys*'] = *random data*;
$arrays['second']['*random_keys*'] = *random data*;
$arrays['keys']['first'] = *list of keys*;
the code:
<select id="selector" name="selected_key" onchange="showContent();">
</select>
<div id="show_selected_option"></div>
<div id="showFirstArrayData"></div>
<div id="showSecondArrayData"></div>
<script>
//both arrays in 1 from php
const arrays = <?php echo json_encode($arrays); ?>;
//keys of first array
const keys_kaunt = <?php echo json_encode(count($arrays['keys']['first'])); ?>;
var text = '<option></option>';
for(var i=0;i<keys_kaunt;i++)
{
text += '<option>' + arrays['keys']['first'][i] + '</option>';
}
//show all options in select
document.getElementById("selector").innerHTML = text;
//show data
function showContent(){
var e = document.getElementById("selector");
var f = e.options[e.selectedIndex].value;
document.getElementById("show_selected_option").value = f;
//first array data
var firstArrayKeys = arrays['first'][f];
var firstKeysOutput= '';
Object.keys(firstArrayKeys).forEach(function (key){
firstKeysOutput += key + arrays['first'][f][key];
});
document.getElementById("showFirstArrayData").innerHTML = firstKeysOutput;
//second array data
var secondArrayKeys = arrays['second'][f];
var secondKeysOutput= '';
Object.keys(secondArrayKeys ).forEach(function (key){
secondKeysOutput += key + arrays['second'][f][key];
});
document.getElementById("showSecondArrayData").innerHTML = secondKeysOutput;
}
</script>
The quastion is how to reset the variable 'f' on changed selector. So it doesnt show the previously selected data if the 2nd array doesnt have the selected key.
thanks, works now. the problem was in generated innerHTML not going away, not in the variable.
If I understand your problem correctly, then you maybe need an if statement.
It sounds like you want to empty the input with id="showSecondArrayData" when arrays['second'] does not contain the key f.
function showContent(){
var e = document.getElementById("selector");
var f = e.options[e.selectedIndex].value;
document.getElementById("show_selected_option").value = f;
// FIRST ARRAY code
//
//second array data
if (f in arrays['second']){
var secondArrayKeys = arrays['second'][f];
var secondKeysOutput= '';
Object.keys(secondArrayKeys ).forEach(function (key){
secondKeysOutput += key + arrays['second'][f][key];
});
document.getElementById("showSecondArrayData").innerHTML = secondKeysOutput;
} else {
document.getElementById("showSecondArrayData").innerHTML = '';
}
}
I'm not an expert in js, so please forgive any mistakes or not keeping with js coding standards.
function showContent(){
document.getElementById("showSecondArrayData").innerHTML = '';
var e = document.getElementById("selector");
var f = e.options[e.selectedIndex].value;
document.getElementById("show_selected_option").value = f;
}
did the trick, ty for the help.

RadComboBox custom text needs to have Outlook behavior

We have a customized Telerik RadComboBox that builds a text string of names separated by semicolons in the textbox field of the combobox by selecting names from the dropdown. We want to improve this and replicate a behavior similar to Outlook where individual names can be selected and deleted from the textbox. The selected names are stored in a hidden input field. Another hidden field carries a CSV list of IDs. Both hidden fields are treated like arrays, and their values have a one-to-one relationship by index. The approach we are considering is to wrap some kind of tag around each name, like a span, so that when a user selects a particular name the whole name will be highlighted and can then somehow be detected. Could this be done by using an ItemTemplate?
The OnClientSelectedIndexChanged event fires the javascript shown, and appends the list of names to the textbox.
function RecipientSelectedIndexChanged(sender, args) {
var combo = $find('<%= rcbRecipients.ClientID%>');
var userid = combo.get_selectedItem().get_value();
var name = combo.get_selectedItem()._text;
var listID = $get("<%= hdnRecipientIdList.ClientID%>").value;
var listName = $get("<%= hdnRecipientNameList.ClientID%>").value;
var listIDArray = new Array();
var listNameArray = new Array();
if (listID != '') {
listIDArray = listID.split(',');
listNameArray = listName.split('; ');
}
listNameArray.pop();
for (var i = 0; i < listNameArray.length; i++) {
listNameArray[i] = listNameArray[i] + '; ';
}
var x = listIDArray.indexOf(name);
if (x == -1) {
listIDArray.push(userid);
listNameArray.push(name + '; ');
listID = listIDArray.toString();
var y = listNameArray.join('');
listName = y;
}
$get("<%= hdnRecipientIdList.ClientID%>").value = listID;
$get("<%= hdnRecipientNameList.ClientID%>").value = listName;
combo.trackChanges();
var item = combo.findItemByText(name);
item.hide();
combo.set_text(listName);
combo.commitChanges();
combo.showDropDown();
}

jQuery.data only saves data from the last Element

i am trying to use jQuery.data() and save an Object to my HTML-Elements. Everytime i add an list-Element to my unordered List it only saves the last object to the specific li-Element. Every other li-Elements saved data gets thrown away!
I've built a little Example. JSBin-Example
On the left, i create a List with an Object saved to it. On the right i am trying to show the data related to the Object.
Why does it only show the Object related to the last HTML-Element?
Working example:
JSBin-Example
That's because you are modifying innerHTML property of the wrapper element. What happens is in each iteration the elements are regenerated, the current elements are removed and the new elements don't have any stored data. Using innerHTML property is the worst way of modifying element contents. You just need to create a li element and append it to the wrapper element:
var random = 0;
// var testObject = [];
function addNewItem(){
random += 1;
var id = "testId" + random;
var text = "This is my " + random + ". text";
var data = {id: id, text: text};
// testObject.push(data);
// You can pass an object as the second argument
// to jQuery constructor and it calls the
// corresponding methods as setter
$('<li></li>', {
text: text + JSON.stringify(data),
id: id,
data: data
}).appendTo('#listId');
}
// bind and trigger click event
$("#add").on('click', addNewItem).click();
I changed
for(var i = 0; i < testObject.length; i++){
var listItem = "";
var id = testObject[i].id;
listItem += liStart + id + liStart2;
listItem += testObject[i].text;
listItem += liEnd;
unorderedList.innerHTML += listItem;
$("#"+id).data(testObject[i]);
}
to this in your updatelist function
//for(var i = 0; i < testObject.length; i++){
var id = testObject[testObject.length-1].id;
listItems += liStart + id+"savedData" + liStart2;
listItems += JSON.stringify($("#"+id).data());
listItems += liEnd;
//}
savedData.innerHTML += listItems;
and it fixed the issue
To help you understand my comment on the question I thought it best I'd give an example of what I meant.
I didn't have enough time to fully go through the solution but wanted to give an example of what I'd call more readable code.
I've added all variables at the top of the function. This will allow you to read and find items much quicker if you needed to alter them.
I've also merged a lot of the string values that you had into an object, namely the li element.
I've never used $.data() as an object before so wasn't really aware how I could use it to set the values in the updateSavedData() $('li'), although the console.log() does show the correct key / values.
$(document).ready(function(){
var uID = 0;
var testObject = [];
var unorderedList = $("#listId");
var savedList = $("#savedData");
var TOL = 0; //TestObjectLength
var textTemplate = "This is my [0] text!";
function addNewItem(){
uID++;
testObject.push({id: uID, text: textTemplate.replace("[0]", uID)});
TOL = testObject.length-1;
updateList();
}
function updateList(){
var li = $('<li>', { id: testObject[TOL].id, data: testObject[TOL], text: testObject[TOL].text });
li.appendTo(unorderedList);
updateSavedData(li.data());
}
function updateSavedData(li){
console.log(JSON.stringify(li));
$('<li>', JSON.stringify(li)).appendTo(savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
Working Example
http://jsbin.com/ralizazahe/1/edit?js,console,output
Anyone that wants to progress on that please do as I'd also like to see how this could be progressed more.
Update
Taken it a step more and refactored to this
$(document).ready(function(){
var $displayList = $("#listId");
var $savedList = $("#savedData");
var textTemplate = "This is my {0} text!";
var uID = 0; //Unique ID
var data = { id: null, text: null }; //Gives a reference
function init(){
uID++;
data = { id: uID, text: textTemplate.replace("{0}", uID) };
}
function addNewItem(){
init();
$('<li>', data).appendTo($displayList);
updateSavedData(data);
}
function updateSavedData(li){
$('<li>', li).appendTo($savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
http://jsbin.com/bajekagoli/1/edit?js,console,output

Javascript pass a variable from function call to innerHtml

Ok, this might be an easy one, im just not sure how to do it. I have a main function where it's taking in an "id". This id is unique and I want to pass it over to another function that is doing a count for me and returns that count to an innerHtml span tag.
Reason for this is because I can have 5 of these open at the same time, but they will have the same span id name "editCommentsCounter"...I want them to be like "editCommentsCounter-id"
function editCommentToggle( id )
{
theRow = document.getElementById("id"+id);
//user = theRow.cells[0].innerHTML;
//date = theRow.cells[1].innerHTML;
com = theRow.cells[2].innerText ;
comLength = theRow.cells[2].innerText.length ;
idx = 2;
maxlength = 250;
count = maxlength - comLength;
// Comment field
cell = theRow.cells[idx];
while( cell.childNodes.length > 0 ) cell.removeChild(cell.childNodes[0]);
spanTag = document.createElement("span");
spanTag.innerHTML = "You have <strong><span id='editCommentsCounter'>"+count+"</span></strong> characters left.<br/>";
cell.appendChild(spanTag);
element = document.createElement("textarea");
element.id="commentsTextArea-"+id;
element.rows="3";
element.value = com;
element.style.width = "400px";
element.maxLength = "250";
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit('editCommentsCounter', maxlength, this);};
cell.appendChild(element);
}
Basically I want to take :
spanTag.innerHTML = "You have <strong><span id='editCommentsCounter'>"+count+"</span></strong> characters left.<br/>";
and make that into something like `span id='editCommentsCounter-' + id
so when I call this:
element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit('editCommentsCounter', maxlength, this);};
I call this above with editCommentsCounter with that id attached to it
See what Im saying?
Use:
document.getElementById("editCommentsCounter-" + id).innerHTML = someVal;
You have a lot there but it seems like that is what you're trying to do to write the innerHTML val. If not please tell me more in comments and I can suggest more.
I see you want to dynamically build a new span, then populate the content. One thing that is puzzling in the beginning you reference the element and concat "id"+id. Have to think about this one so apologies for too quick response; was just looking at your end result.
Setting the unique ID:
var spanTag = document.createElement("span");
spanTag.id = 'editCommentsCounter-' + id;
spanTag.innerHTML = 'You have ...' + count + '...';
document.body.appendChild(spanTag);
I hope this helps!

Categories

Resources