Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    2
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Help newguy...Event listeners and Forms

    I hate to be that annoying person who comes here and asks such a broad series of questions that I could eventually figure out on my own through proper searches and studying. It is just I am really frustrated with my school for forcing me to take my core courses online, with no choice of a classroom environment, and I have really been struggling to force myself through some of these programming languages.

    My assignment is to make an array that will mimic a database, filled with albums and their information, as objects, within the array.

    I must create a series of functions that will return a simple user search request.

    I will spare you ALL of my code and just give you small instances of some of my functions, event listeners, and the html forms.

    Ok, one of my functions, this function will access my array and object points, matching albums with similar categories of music.

    Code:
    function GetAlbumByCat(categoryid){
    
    for (i = 0;i < database.length;i++){
    	var catToSearch = document.getElementById('SearchCategory').value;
    		if (database[i].Category == catToSearch ){
    			alert(database[i].Category);
    		}
    	}
    }
    My Event Listener

    Code:
    windows.onload = function(){
    
    var catToSearch = document.getElementById('SearchCategory').value;
    
    if (catToSearch == Null){
    
    
        document.getElementById('theForm1').onsubmit = GetAlbumByArtist(artistid);
    	}else {
    	document.getElementById('theForm2').onsubmit = GetAlbumByCat(artistid);
    	}
    	
    }
    My HTML Form
    Code:
    	<form action="#" method="post" id="theForm2">
    	<label for="SearchCategory">Search By Category</label><input type="text" name="SearchCategory" id="theForm1" required>
    	<input type="submit" Value="SearchCategory" id="SearchB">
    	</form>
    Question #1. Does my function need that parameter?

    Question #2. Is my event listener accessing the correct parts of the form element?

    Question #3. Does my html form make any sense? I mean you can see I created a ton of Id="" statements simply because I do not understand where the event listener is accessing the users search request, and returning it to the function.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    1. That function doesn't need that parameter with the code you currently have in the function as nothing in the function currently references it. Perhaps whatever code is going to be replacing the debugging alert() call will use it.

    2. You don't have any event listeners in your code at all. event Listeners are added using addEventListener() (and attachEvent() for IE8). You do have several event handlers. The onload event handler would be unnecessary if you move the JavaScript to the correct p-lace in the page (immediately before the </body> tag). Of the two onsubmit handlers only the one attached to the form tag will work as that is the only tag that has that event triggered.

    3. Your form is missing the wrapper around the acttual fields inside the form. Also the for attribute on the label has to match the id attribute of the input field as that is how the two are linked together. The submit button doesn't need an id.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    steme (02-25-2013)

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,857
    Thanks
    78
    Thanked 4,416 Times in 4,381 Posts
    Ummm...the code, as written, makes no sense at all.
    Code:
    windows.onload = function(){
        var catToSearch = document.getElementById('SearchCategory').value;
    First of all, there is no such thing as windows.onload. I will assume you meant to write window.onload.

    But then that is telling your code to find out what the user has entered into the SearchCategory field...before the user can ever possibly have done so!!!

    That is, window.onload runs AS SOON as the entire page is loaded by the browser and before any human input to the <form> is even possible!

    But wait, we aren't done:
    Code:
        if (catToSearch == Null){
    There is no such thing as Null in JavaScript. (Well, you *could* have a variable by that name, but that would be a really poor choice.)

    I will assume you meant to write null. Yes, JavaScript is case sensitive.

    BUT... But catToSearh is the .value of a <form> field, and .value properties are *NEVER* null.

    So that condition will *ALWAYS* be false.

    And so, in total, your code is exactly the same as if you had coded
    Code:
    window.onload = function( )
    {
        document.getElementById('theForm2').onsubmit = GetAlbumByCat(artistid);
    }
    Last edited by Old Pedant; 02-25-2013 at 09:06 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    steme (02-25-2013)

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,857
    Thanks
    78
    Thanked 4,416 Times in 4,381 Posts
    And not to ask a silly question, but... How is the search by artist supposed to work when you don't have a <form> field for the artist's name?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    2
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Update with a wider view of some simplified code.

    I can understand the logic of most simple programming(I think), I am just having trouble wrapping my head around how html and javascript are talking to each other.

    Edit: I am starting to think my array might be bad, maybe I should of tested it before posting.

    Code:
    <body>
    	<div>
    	<form id="theForm">
    	<label for="SearchCategory">Search By Category</label><input type="text" name="SearchCategory" required>
    	<input type="submit" Value="Search Category">
    	</form>
    	</div>
    	<script src="js/store.js"></script>
    </body>
    Code:
    var database = new Array();
    
    var  atFolsomPrison = {id: 1, Artist: 'Johnny Cash', Price: 9.99, Release: 1968, Quantity: 12, Category: 'Classic'};
    var lynardSkynyrd = {id: 3, Artist: 'Lynard Skynyrd', Price: 8.99, Release: 1974, Quantity: 45, Category: 'Rock'};
    var physicalGraffiti = {id: 4, Artist: 'Led Zeppelin', Price: 8.99, Release: 1976, Quantity: 122,  Category: 'Rock'};
    var coda = {id: 5, Artist: 'Led Zeppelin', Price: 8.99, Release: 1977, Quantity: 11, Category: 'Rock'};
    
    database.push(atFolsomPrison);
    database.push(lynardSkynyrd);
    database.push(physicalGraffiti);
    database.push(coda);
    
    function GetAlbumByCat(){
    
    for (i = 0;i > database.length;i++){
    	var catToSearch = document.getElementById('SearchCategory').value;
    		if (database[i].Category == catToSearch ){
    			alert(database[i].Category);
    		}
    	}
    }
    
    function init(){
    
    document.getElementById('theForm').onsubmit = GetAlbumByCat;
    
    }
    Last edited by steme; 02-25-2013 at 09:44 PM.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,857
    Thanks
    78
    Thanked 4,416 Times in 4,381 Posts
    Starting to get there.

    But if you use ).onsubmit = GetAlbumByCat; then unless your GetAlbumByCat() function does return false then your <form> *WILL* submit and that means your page will get wiped out when it is reloaded from the server.

    It usually makes more sense, when you don't EVER want a <form> to submit, to *NOT* use onsubmit. Instead, just use an <input type="button"> and use the onclick of the button.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    steme (02-26-2013)

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,857
    Thanks
    78
    Thanked 4,416 Times in 4,381 Posts
    And here's the more modern way to do all that:
    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <div>
        <form id="theForm">
    	<label>Search By Category
                <input type="text" name="SearchCategory" required>
            </label>
    	<input type="button" Value="Search Category" name="doIt">
        </form>
    </div>
    
    <script type="text/javascript">
    (
      function( ) /* master anonymous function */
      {
    
          var database = [
              {id: 1, Artist: 'Johnny Cash', Price: 9.99, Release: 1968, Quantity: 12, Category: 'Classic'},
              {id: 3, Artist: 'Lynard Skynyrd', Price: 8.99, Release: 1974, Quantity: 45, Category: 'Rock'},
              {id: 4, Artist: 'Led Zeppelin', Price: 8.99, Release: 1976, Quantity: 122,  Category: 'Rock'},
              {id: 5, Artist: 'Led Zeppelin', Price: 8.99, Release: 1977, Quantity: 11, Category: 'Rock'}
          ];
    
          var form = document.getElementById("theForm");
          form.doIt.onclick = function( )
          {
              // do this ONCE!  Not each time through loop!
              var catToSearch = form.SearchCategory.value;
              for (i = 0;i > database.length;i++)
              {
                  if (database[i].Category == catToSearch )
                  {
    		  alert(database[i].Category);
                  }
    	  }
          }
      } // end of anonymous function
    )(); // self-invoke anonymous function
    </script>
    </body>
    If you only have 4 albums, the way you create the "database" is fine.

    But if you 400, that could get tedious. You might want to do something like this:
    Code:
    // create a CONSTRUCTOR for an album object:
    function Album( ID, artist, price, release, qty, cat )
    {
        this.id     = ID;
        this.Artist = artist;
        this.Price  = price;
        this.Release = release;
        this.Quantity = qty;
        this.Category = cat;
    }
    
    // the use the constructor repeatedly:
    var database = [
        new Album( 1, 'Johnny Cash', 9.99, 1968, 12, 'Classic' ),
        new Album( 3, 'Lynard Skynyrd', 8.99, 1974, 45, 'Rock' ),
        ...
    ]
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    steme (02-26-2013)


  •  

    Posting Permissions

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