SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,388
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Learning about arrays in JS

    I made a form to accept input:

    HTML Code:
    <div>
    <form id="formColor" method="POST" action="TestingHTML.html">
    <p>Add new color:<br />
    <input name="newColorInput" type="text" value="">
    <input type="submit" value="GO" onClick="sampleArray()">
    </p>
    </form>
    </div>
    I have JS to put the input into an array and show it in the console:

    Code:
    function sampleArray() {
        "use strict";
    // make array
    	var colors2 = [];
    // obtain new array item from form
    	var form = document.getElementById('formColor');
    	var newColorInput = formColor.newColorInput.value;
    	var newColor = newColorInput;
    	colors2.push(newColor);
    console.log ("new color = " + newColor);
    </script>
    Then I added to just above </body>:

    Code:
    <script>
    /* execute the functions */
    sampleArray();
    </script>
    When I enter a word, it merely flashes briefly on the screen and console. How do I code to get the word to remain in the array so it stays on the screen?
    Steve Husting

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,446
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Hi Steven,

    The problem is that you're not preventing the form from being submitted, which is why the screen refreshes and your console output disappears. Try this:

    Code JavaScript:
    (function(){
    	"use strict";
     
    	var colors = [],
    		form = document.getElementById('formColor');
     
    	form.addEventListener("submit", function(e) {
    	        e.preventDefault(); // prevents the form from submitting
    		var newColor = formColor.newColorInput.value;
    		colors.push(newColor);
    		console.log ("new color = " + newColor);
    		console.log (colors.join(', '));
    	}, false);
    })();

    This attaches a submit handler to form, so you don't need that inline onClick="sampleArray()" JS in your HTML markup. I've also outputted the contents of the array as a string each time, so you can see that the colours are being added.

  3. #3
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,043
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Well, what is causing your immediate problem is the fact that the form is submitting, hence the results being only displayed briefly on the console.

    You can normally solve this by passing a reference to the event that triggered the function to the function and preventing the browser's default action:

    Code:
    function someFunction(e) {
      e.preventDefault(); 
      ...
    }
    However, you have attached a click handler to a button within the form and this is going to trigger the submit regardless.

    ... and there is a better way to do this:

    Remove the inline click event handler and attach a submit event handler to the form unobtrusively:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Form submit</title>
      </head>
    
      <body>
    
      <div>
        <form id="formColor" method="POST" action="TestingHTML.html">
          <p>Add new color:<br />
            <input name="newColorInput" type="text">
            <input type="submit" value="GO">
          </p>
        </form>
      </div>
    
        <script>
          function getColour(e) {
            e.preventDefault();
            var newColor = this.newColorInput.value;
            console.log ("new color = " + newColor);
          }
    
          var form = document.getElementById('formColor');
          form.addEventListener("submit", getColour, false);
        </script>
      </body>
    </html>
    I know it might seem like a bit of a hefty read, but I really recommend this: An Introduction To DOM Events

    If you have any questions, just let me know.

  4. #4
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,388
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    fretburner, That code looks a bit advanced for my current stage, but thanks!
    Steve Husting

  5. #5
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,043
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    What are you having trouble with?
    The code I posted is only five lines long, so we could step through it if you like.

    Edit:

    Ok, you added the word "fretburner"

  6. #6
    SitePoint Wizard
    Join Date
    Feb 2007
    Location
    Southern California
    Posts
    1,388
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    The sample code works great! I just wasn't introduced to the e.preventDefault(); in the book yet, so your code threw me off. I have another question about this code, but I'll put it in another post because it's different.
    Steve Husting


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •