1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

For loop through array - javascript

Discussion in 'JavaScript' started by mrki444, Jan 6, 2016.

  1. #1
    I'm trying take loop through array and print all elements from array, but I have problem with function getElementbyId().innerHTML

    Here is prtsc of site.
    [​IMG]

    When you click on blue button, below 'Ticket' should print
    Real Madrid - Barcelona, Chelsea -Man.Utd, PSG - Lyon
    but insted it print
    Real Madrid - BarcelonaReal Madrid - BarcelonaChelsea - Man. United
    Here are codes:
    Javascript in head:
    <script>
        <!-- np=array with names of clubs, odd=array with odds -->
    var y, x, cnp;
    var np = [];
    var odd = [];
    var text;
    function myFunction(a,b) {
      
            x = document.getElementById(b).innerHTML;
            y = document.getElementById(a).innerHTML;
            cnp = np.indexOf(x);
            if (cnp == -1)
            {
                        np.push(x);
                        odd.push(y);
            }
            else
            {
            odd[cnp]=y;
            }
            var i;
            for (i = 0; i < np.length; i++) {
                text += np;
            }
            document.getElementById("ticket").innerHTML=text;
    }
    </script>
    
    Code (markup):
    HTML:
    
    <header>
                                    <h2>Sport</h2>
                                </header>
    
                                <p>
                                <table>
                                <tr id="ponuda">
                                <td id="111">Real Madrid - Barcelona</td>
                                <td><button id="1" onclick="myFunction(1,111)">1,20</button></td>
                                <td><button id="2" onclick="myFunction(2,111)">2,00</button></td>
                                <td><button id="3" onclick="myFunction(3,111)">2,40</button></td>
                                </tr>
                                <tr id="ponuda">
                                <td id="222">Milan - Inter</td>
                                <td><button id="4" onclick="myFunction(4,222)">1,60</button></td>
                                <td><button id="5" onclick="myFunction(5,222)">2,10</button></td>
                                <td><button id="6" onclick="myFunction(6,222)">1,90</button></td>
                                </tr>
                                <tr id="ponuda">
                                <td id="333">Chelsea - Man. United</td>
                                <td><button id="7" onclick="myFunction(7,333)">2,66</button></td>
                                <td><button id="8" onclick="myFunction(8,333)">3,11</button></td>
                                <td><button id="9" onclick="myFunction(9,333)">1,11</button></td>
                                </tr>
    
                                <tr id="ponuda">
                                <td id="444">PSG - Lyon</td>
                                <td><button id="10" onclick="myFunction(10,444)">1,85</button></td>
                                <td><button id="11" onclick="myFunction(11,444)">2,48</button></td>
                                <td><button id="12" onclick="myFunction(12,444)">2,05</button></td>
                                </tr>
                                </table>
                                </p>
    <p>Ticket</p>
                              
                                <table id="ticket">
    
                                </table>
    
    Code (markup):
    Shouldn't document.getElementById("ticket").innerHTML in for loop overwrite everything in id="ticket"?
     
    Solved! View solution.
    mrki444, Jan 6, 2016 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    I'm on my phone, so not really a good place to write code, but that code is horrible. You have multiple rows with the same id, onClick functionality, tables within på elements...
    I'm pretty sure that code can be vastly improved
     
    PoPSiCLe, Jan 6, 2016 IP
  3. mrki444

    mrki444 Greenhorn

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    I don't think I have multiple rows with same id.

    What's the problem with onClick functionality?

    I will remove tables from p tag.
     
    mrki444, Jan 7, 2016 IP
  4. #4
    It's a good first pass

    I made some changes to it here: https://jsfiddle.net/8b0yd73n/1/
    • for starters "ticket" shouldn't have been a table, I made it a div
    • Your table of betting odds didn't need to be inside a paragraph
    • I learnt to code in the days of reserved words - I'm assuming they still matter so have changed the variable "text" to "ticketInfo" and instead of it being global I've made it a local variable
    • I've added commas between each of the club names when the user has pressed more than one
     
    sarahk, Jan 7, 2016 IP
  5. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #5
    I cleaned it up a bit more, among other things, I removed the duplicate IDs on the <tr> (ponuda, I think it was), and replaced them with the ID previously found on the <td> with the game name - then I removed all the onclick-events, and placed that code in the JS instead. It's pure JS, which I'm not that fluent in (my strength is in jQuery), so it's probably not as effective as it could've been. https://jsfiddle.net/8b0yd73n/2/
     
    PoPSiCLe, Jan 7, 2016 IP
  6. mrki444

    mrki444 Greenhorn

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #6
    Thank you very much!!!
    But after everything I see that mistake was print in table and not in div.
     
    mrki444, Jan 7, 2016 IP
  7. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665
    #7
    Maybe, but try to learn from what we're pointing out.
     
    sarahk, Jan 7, 2016 IP
  8. mrki444

    mrki444 Greenhorn

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #8
    Yes, I will.
     
    mrki444, Jan 7, 2016 IP
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #9
    As others have said you've got a lot of just plain nonsense in the markup -- there's more that goes into a table than just TR and TD... like your H2 should probably be a <caption>, you've got paragraphs for... well, christmas only knows what, you've gone about things the hard way... and for the life of me I don't get what you expect innerHTML to actually do, but I'm pretty sure whatever it is, this isn't how you go about it.

    Of course you've also got the pointless HTML 5 crap that makes me want to track down the whatWG members with a shotgun; header wrapping a heading.... and people wonder why I call HTML 5 mouth-breathing halfwit nonsense! :(

    ...and not only do you re-use the same ID multiple times, you have ID's starting with numbers. ID's can't start with a numeric character!

    First step would be to drag that markup out of the 1990's. If you are using "onclick" you are likely doing something wrong. None of those ID's even serve a legitimate purpose since this is all scripttardery, your titles should be TH not TD with a scope="row" attribute, and the scripting should be attempting to find the parent element via the DOM, not dicking around with innerHTML.

    See, in JS there's something called the "Document Object Model" -- and that's where you should be pulling the title and values from, not the markup. Generally speaking if you are attempting to read innerHTML, you are doing something WRONG!

    So first, the markup:
    <table id="ticketSelector">
    	<caption>Sporting Event Seating</caption>
    	<thead>
    		<tr>
    			<th scope="col">Event</th>
    			<th scope="col">Upper</th>
    			<th scope="col">Club</th>
    			<th scope="col">Lower</th>
    		</tr>
    	</thead><tfoot>
    		<tr>
    			<th colspan="4" class="tFootTitle">Selected Tickets</th>
    		</tr>
    	</tfoot><tbody>
    		<tr>
    			<th scope="row">Real Madrid - Barcelona</th>
    			<td><button value="Upper">1,20</button></td>
    			<td><button value="Club">2,00</button></td>
    			<td><button value="Lower">2,40</button></td>
    		</tr><tr>
    			<th scope="row">Milan - Inter</th>
    			<td><button value="Upper">1,60</button></td>
    			<td><button value="Club">2,10</button></td>
    			<td><button value="Lower">1,90</button></td>
    		</tr><tr>
    			<th scope="row">Chelsea - Man. United</th>
    			<td><button value="Upper">2,66</button></td>
    			<td><button value="Club">3,11</button></td>
    			<td><button value="Lower">1,11</button></td>
    		</tr><tr>
    			<th scope="row">PSG - Lyon</th>
    			<td><button value="Upper">1,85</button></td>
    			<td><button value="Club">2,48</button></td>
    			<td><button value="Lower">2,05</button></td>
    		</tr>
    </table>
    Code (markup):
    The TH and SCOPE attributes are important so that you have table HEADINGS with their relationships set up, that way people on non-visual UA's or non-mouse/keyboard devices aren't left out in the cold. Remember with HTML, accessibility is job 1. I'm treating it all as a table for reasons that will become clear shortly, but for now just be aware that if this is actually tabular data (which it seems to be) then you should use THEAD, and TBODY... and since it's tabular data, why not put the results in TFOOT? It may seem counterintuitive that TFOOT goes before TBODY in a table, but that's because the result is supposed to be paginated in print -- which is to say if you print it out the contents of TFOOT will appear on every page if the table spans multiple instances, as such it's more efficient for the browser to know what's there FIRST.

    Again, WAY more tags belong in a TABLE than just TR and TD!

    You'll notice I'm remarkably lean on classes and ID's -- this is thanks to bothering to leverage the DOM for the scripting and child selectors in the CSS.

    The script will need to grab hold of all button tags inside #ticketSelector and attach the events itself. IDEALLY this should actually be inside a form so that scripting off hitting the buttons is treated as a submit, so that you can make it work scripting off FIRST, but for now I'll just make the scripted example.

    Gimme a few and I'll toss together a working demo on my site with the full source.
     
    deathshadow, Jan 10, 2016 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #10
    You ever go overboard on something simple? I may have done that. I added the capacity to choose multiple items and remove them from the result list.

    Live demo here:
    http://www.cutcodedown.com/for_others/mrki444/template.html

    As with all my examples the directory:
    http://www.cutcodedown.com/for_others/mrki444/

    ... is wide open for easy accesss to the gooey bits and pieces, and I dumped everything into a .rar so you can DL it in one fell swoop.

    http://www.cutcodedown.com/for_others/mrki444/ticketSelector.rar

    The CSS:
    http://www.cutcodedown.com/for_others/mrki444/screen.css

    .. is fairly straightforward. I used my stock reset and tried to mimic your appearance though I "cleaned it up" a bit. The only big things that really need explanation in there is the user-select and browser specific instances of same. I did this so that if people click REALLY FAST on the button it won't trip the "select text" part of the browser. I also remove the outline (and border in FF) from buttons on keyboard navigation so we can style it the same as the hover effects!

    The scripting:
    http://www.cutcodedown.com/for_others/mrki444/ticketSelector.js

    ... is where the real magic happens. I wrapped everything in a self starting function so that this script will not conflict with any other scripts on the page. I pass document to this script as "d" just so I'm not typing "document" and endless number of times, and it actually runs faster this way. (trick I picked up from Google's various scripts!)

    The first portion are some handy stock functions I use when doing something like this. DOM manipulation can be tricky, as can event handling so having some nice cross-browser functions to remove those headaches are a must have; I just don't believe that it should ever become big enough to be a "framework" nor should it try and change how JS actually works.

    'eventAdd' is pretty self-explanatory. 'eventProcess' makes sure we actually have the event object when an event is triggered, that event.target is set up properly, and allows us to prevent all bubbling, cascading, and other such results if we so need. (which we do here).

    'make' creates a dom element, with the content (an object or string) plugged into it, attached to the parent dom element if so declared, with any attributes in the attr object assigned. Using this instead of innerHTML means that while scripting may take longer, it will actually run faster as the browser's HTML parser doesn't need to get involved!

    'nodeAssignAttr' is a self recursive function that allows us to pass complex objects like style.color or so forth. We don't really need it's full functionality here, but I included it for completeness sake.

    'nodeFirst' looks for the first element node (nodeType 1) that has the tagName we are looking for. I have a more complex version of this function, I dumbed it down for this example.

    Typically we want to avoid innerHTML, last thing we want is markup when we are looking for values -- but innerText and TextContent are inconsistent across browsers, so I have the 'nodeText' function to pull the appropriate one. The two do NOT handle the presence of linefeeds in the same manner, but that's not an issue for what we're doing here.

    So, that's our lib functions, onto the functionality.

    First I grab the table, then all buttons in the table, then the tfoot. See how 'nodeFirst' makes grabbing that tfoot simple without resorting to an ID? Should only be one TFOOT in a table anyways so...

    The next two functions are our event handlers. Not all browsers pass the event object the same way (thanks IE!) so we use eventProcess to make sure 'e' is set properly, and to kill any event bubbling up through the document.

    I make both functions standalones instead of anonymous since they will be assigned and used multiple times. This is faster on execution and uses less memory.

    'buttonClickRemove' is a function our 'remove' buttons will call when clicked. These buttons will be inside a TD, which will be inside a TR... when we click on "remove" we want to get rid of the TR, so that's just find the TR (button.parentNode == TD, button.parentNode.parentNode == TR), then tell the TR's parentNode (tfoot) to remove the TR.

    'buttonClickAdd' is assigned to all your ... whatever those values are. I guessed WILDLY as to their meanings and just treated them as prices. (I know next to nothing about seating at sporting events -- I'm a theatre guy -- was tempted to add a mezzanine column).

    For now to keep it simple, I leverage that 'make' function to create our new DOM elements. First I create our TR with the heading inside it, copying the content of the heading for the button that was clicked on. Again we use parentNode to work our way up to the button's parent TR, then look for the first TH inside it with 'nodeFirst' -- to then pull the 'nodeText'. The TR is created as a child of tfoot.

    I store that TR in a variable so we can make the TD. I pull the value of the button put that in a TD, pull the text of the button, give that a TD, then make a final TD containing a button to remove the element.

    NORMALLY one does not simply assign 'onclick' directly since you never know if any other scripting is trying to attach handlers as well, but in this case since we're making a brand spanky new element no other scripts even have a chance to hook it yet. As such we can pass that attribute value and boom, click on the "remove" button and buttonClickRemove is called.

    Finally we have the loop to assign all those buttonClickAdd events to the buttons inside TBODY.

    A wee bit heftier and complex, but gives you the full functionality I suspect something like this would/should have. (since who's only going to pick one item?)

    In THEORY thanks to how it's written, the scripting should gracefully degrade back all the way to IE 5.5 -- and I see no reason for the markup/css to not degrade in a useful manner in legacy IE either. As I often say, if people on outdated browsers don't get shadows and rounded corners, OH WELL.

    But again, was guessing wildly since I'm not familiar with your data, and an understanding of the data/content being manipulated is the determining factor across the board on implementing HTML, CSS and JavaScript.

    In any case, hope this helps -- or at least you or others can learn from it.
     
    deathshadow, Jan 10, 2016 IP
    sarahk likes this.
  11. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #11
    I didn't see that as seating - I saw it as betting (odds) Home, Away, Tie (I'm guessing)
     
    PoPSiCLe, Jan 10, 2016 IP
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #12
    Which means nothing to me as again, I'm about as friendly to sporting events as I am Bootstrap and jQuery. It's probably not that though since there's only two numbers, not three... or are you thinking the columns themselves as those three?

    Again, we don't know what the data actually is or means, something that should be established and clearly labelled LONG before diving into scripttardery.
     
    deathshadow, Jan 10, 2016 IP