Attempting to build a resume creator as a project for codeacademy.
I'm using a button to "save" the user's input to an array so it can later be appended into the resume.
However, I'm failing at getting the data to "save" to the array. I've looked at similar questions here on stackoverflow and I cannot for the life of me figure out what I am doing wrong.
here's my fiddle
specific code block I'm having trouble with:
$('#experiencesave').click(function(){
for (var i = 0; i < jobs; i++){
jobtitle.push = $('#jobtitle'+i).val();
}
$('#morejobs').append(jobtitle);
});
Well, .push [MDN] is a function which has to be called:
jobtitle.push($('#jobtitle'+i).val());
As an alternative solution, instead of using a for loop, you might want to use .map to collect the values:
var jobtitle = $('input[id^=jobtitle]').map(function() {
return this.value;
}).get();
I don't see a reason to give each of those input elements an ID though. Just give them a class. That makes it a bit easier to bulk-process them later. E.g. the selector could then just be $('input.jobtitle').
Related
I have a JSON response from a server, which returns me a array with 32 objects (in this case). Something like this:
[{object1},{ object2},{ object3}, etc].
Each object have some info that I use to populate an html template. For that, I just use a simple loop:
for(var i = 0; i < api_empresaListar.length; i++)
{
var item = api_empresaListar[i];
var htmls;
htmls = $('...lots of html code');
...
Then it’s just a simple matter of finding/changing the values, and append items on the DOM. Everything works fine. BUT, for some next parts of the code, I would like to access all the info from the object I used to build the html elements (I just show part of the info). So, after searching a lot, I tried to use data, like this:
var tp = htmls.find(".rl_grupo"); // the main div of each html element created in the loop
$(tp).data('key', api_empresaListar[i]); // here, I expected to just insert the object data in each created item.
But when I try it in the console, I got the object info as expected, but always from the last element in the array. Why is that happening? I believe it might be something stupid, but I can’t figure it out.
So, any ideas on how to solve this, or another method to make this work is appreciated. I made it work by setting some "display:none" placeholder html tags and populate those with the info I need later, but looks like a poor solution...
You should not set your htmls variable in the loop. I think that you crush its content every turn, that's why you only have the last item. You should do something like this:
var htmls = $('<div></div>');
for(var i = 0; i < api_empresaListar.length; i++) {
htmls.append($('...lots of html code'));
}
How about setting an index number on each element inside of your html creating code, then iterating over the $('.rl_grupo') elements, like this?
$('.rl_grupo').each(function(){
var index = $(this).data('index');
var currentData = api_empresaListar[index];
$(this).data('key', currentData);
})
This is my controller code:
var domainList=angular.copy($scope.busdomain);
if(domainList!=null){
domainList[0].childNode.sort();
//For finding out the length of list
for (var i = 0; i < domainList[0].childNode.length; i++) {
//Here I want to add a check that I can get name only of objects in my list
//Please see the attached Object screenshot for better understanding
if (domainList[0].childNode[i].name!=null) {
var name=domainList[0].childNode[i].name;
domainList[0].childNode.splice(i,1,name);
$scope.busdomainname=domainList[0].childNode;
}
}
I want to get the list of object and take out its name and add to $scope.busdomainname as I need to display only name on another page.
Is there any way to do this. Please help me out. Thanks in advance
Try underscore library example instead of going the hard way. It provides useful functions like this. Your case
_.pluck (domainList, "name");
I'm currently trying to populate a selection list from an external javascript array. It works but I'm trying to populate only certain values using an ID column, which is failing. I'm using check-boxes and an 'If' statement to see which box is checked, and populate the appropriate array values based on this selection. I'm then using another 'If' within a for loop to match the ID value in the array, and add the matching values to the selection. However, it seems that it is completely disregarding the condition and reading the entire array in to selection list. It could be an obvious mistake with my code as I am only a novice.
function populateIslandList () {
var form = document.forms["island_form"];
var islands = form.islands;
if (islands[0].checked){alert("works");
for (i = 0; i < pislands.length; i++)
if (pislands[i][1] = 1){
document.forms["location"].islands.options[i] =
new Option(pislands[i][0], i)}};
if (islands[1].checked){alert("works");
for (i = 0; i < pislands.length; i++)
if (pislands[i][1] = 2){
document.forms["location"].islands.options[i] =
new Option(pislands[i][0], i)}};
}
Your first mistake is here:
var islands = document.getElementById("island_form");
document.getElementById() returns a single DOM element, not a list of objects. So, thus islands[0] and islands[1] are going to be undefined and islands[0].checked will make a script error.
You can only have one DOM element with a given id. You can have multiple elements with a class name so maybe you should switch to using class names and be using document.getElementsByClassName("something")
FYI, you should be looking in the browser error console or debug console to see script errors as this should have given you an indication of some trouble here.
Thanks for giving this a look. I'll start with a quick image. Clicking on any of the red-boxed search results seems to return the <div> for the item directly above it.
Here I clicked on 1613 CAROUSEL CIR, but the event returned the id/content for the item representing 1612..
Sometimes it's even weirder, for example, every item following 1420 might point back to 1420. So it's not always a conflict with a <div> and it's immediate neighbor, although that's usually the case.
I've been unable to find any definite pattern in this behavior. Sometimes it's just one or two items in the list; sometimes most of the list is affected, with "a good portion" of results pointing to one particular div.
There's only one true consistency--typically the first several items work as expected, and short lists will be 100% correct. But really long lists (50+) are not necessarily worse than semi-long lists (20+).. :/
The code building the search results iterates over JSON data retrieved by a JQuery $.ajax() call, and this is the relevant code building the visible search results:
if( result.d.length > 0 )
{
var i=0;
for(i; i<result.d.length; i++)
{
// ..there's a bunch of irrelevant code here to set the map bounds..
// ..then I build the HTML using JQuery like this
//
var date = new Date();
var divID = "searchItemDiv" + date.getTime().toString();
var $searchItemDiv = $( "<div id='" + divID + "' class='searchItemDiv'>"+result.d[i].Description+"</div>" );
$searchItemDiv.data('itemData', result.d[i]);
$searchItemDiv.bind('click', onSearchItemClick);
$( "#searchResults" ).append($searchItemDiv);
}
}
While I don't suspect the event handler is the issue, the relevant code there looks like this:
function onSearchItemClick(event)
{
if( event.target.id.toString() !== '' )
{
// I clicked 1613, but event returned DIV with text of "1612"??
//
var item = $('#'+event.target.id.toString()).data('itemData');
alert( event.target.id.toString()+"\n"+
$('#'+event.target.id.toString()).text() );
// ..more irrelevant stuff to show a popup of property data..
}
}
FireFox, Chrome, and IE all demonstrate the same behavior, so it's not browser-specific.
I'm relatively sure this is not the product of a race condition during the render phase, but I'm not comfortable-enough with JavaScript to know that for certain.
I'm pretty baffled by this. FWIW, I'm a former Flex & C# developer and relatively new to JavaScript/JQuery development, so there may be a gotcha related JavaScript contexts and/or JQuery that I'm stepping into.
I would say, instead of binding the click function within a for-loop, just select all of the searchItemDiv's after the for-loop binds the data to them, and register a click function on all of them at once. You don't need a separate line to define variable i, just do it in the for statement. I also wouldn't try to generate random IDs with new Dates, that just seems unnecessary. Registering all click functionality at once will also make your click handler much simpler:
if( result.d.length > 0 )
{
for(var i = 0; i<result.d.length; i++)
{
// ..there's a bunch of irrelevant code here to set the map bounds..
// ..then I build the HTML using JQuery like this
// select the i'th searchItemDiv
$searchItemDiv = $($('.searchItemDiv')[i])
// give it the data
$searchItemDiv.data('itemData', result.d[i]);
$( "#searchResults" ).append($searchItemDiv);
}
// then register all the click handlers at once, very simple
$('.searchItemDiv').bind('click', function() {
var item = $(this);
alert(item.text());
});
}
--EDIT--
also, do the searchItemDivs already exist or are you trying to create them?
if you're trying to create them, you might want this in the for-loop instead:
for(var i = 0; i<result.d.length; i++)
{
// ..there's a bunch of irrelevant code here to set the map bounds..
// ..then I build the HTML using JQuery like this
// create a searchItemDiv
$searchItemDiv = $('<div class="searchItemDiv"></div>')
// give it the data
$searchItemDiv.data('itemData', result.d[i]);
$( "#searchResults" ).append($searchItemDiv);
}
I'm guessing that is what you want to do.
I think your problem depends on your searchItemDiv id.
Using the date doesn't ensure ids are unique so when you retrieve the object by id it will return an element (probably the first) with the same id.
Make sure to assign unique id on your elements.
First question ever, new to programming. I'll try to be as concise as possible.
What I want to do is to create a bunch of children inside a selected div and give each of them specific html content (from a predefined array) and a different id to each child.
I created this loop for the effect:
Game.showOptions = function() {
var i = 0;
Game.choiceElement.html("");
for (i=0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children()[i].attr("id","choice1");
}
};
Using the predefined values of an array:
Game.event[0] = { text: "Hello, welcome.",
options: [{response: "<a><p>1. Um, hello...</p></a>"},
{response: "<a><p>2. How are you?</p></a>"}]
};
This method does not seem to be working, because the loop stops running after only one iteration. I sincerely have no idea why. If there is a completely different way of getting what I need, I'm all ears.
If I define the id attribute of each individual p inside the array, it works, but I want to avoid that.
The idea is creating a fully functional algorithm for dialogue choices (text-based rpg style) that would work with a predefined array.
Thanks in advance.
The problem with your loop as I see it could be in a couple different places. Here are three things you should check for, and that I am assuming you have but just didn't show us...
Is Game defined as an object?
var Game = {};
Is event defined as an array?
Game.event = new Array();
Is Game.state returning a number, and the appropriate number at that? I imagine this would be a little more dynamic then I have written here, but hopefully you'll get the idea.
Game.state = 0;
Now assuming all of the above is working properly...
Use eq(i) instead of [i].
for (var i = 0; i<Game.event[Game.state].options.length; i++) {
Game.choiceElement.append(Game.event[Game.state].options[i].response);
Game.choiceElement.children().eq(i).attr("id","choice" + (i + 1));
}
Here is the JSFiddle.