SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast polyhedra's Avatar
    Join Date
    Nov 2011
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    On a submit, greet user

    Hello hope all is well,

    So I am trying to greet a user with "Hello name" when they enter their name and click submit. Unfortunately, each click appends another "Hello name" instead of overwriting the previous h2 tag in main.
    HTML Code:
    // When the page finishes loading.
    window.onload = function () {
      // Initializing variables.
      var button_submit = document.getElementById("submit_section");
      
      button_submit.onclick = function () {
        // Initializing variables.
        var greeting = "Hello "; 
        var main = document.getElementById("main");
        var output = document.createElement("h2");
        var text_section = document.getElementById("text_section");
        var name = text_section.value;
        
        // Program logic
        greeting += name;
        output.innerHTML = (greeting);
        
        // Output the message.
        main.appendChild(output);
      };
    };
    The problem is at the output message part, I'm not sure what to do differently.
    Thanks,
    Polyhedra (Dan)

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Currently your appendChild is adding a new one each time that code runs.

    What you can do instead, is to check if its already on the page, and if it is to then use that one.

    Code javascript:
    function addGreeting(target) {
        var h2 = ...
        h2.classList.add('greeting');
        target.appendChild ...
    }
     
    var output = document.querySelector('.greeting');
    if (!output) {
        output = addGreeting(main);
    }
    ...
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •