0

Though I have seen similar questions here with solutions, yet I was not able to figure out the problem with my code. Can someone please help look into it and tell me what I'm not doing right. I am trying to add user input to the list using array functions. I want to already have 3 elements in the array before the user input and later remove the added inputs with another array method. but first to add the inputs has been my challenge. I have added my code for view.


    var domTarget = id => {
  return document.getElementById(id);
};
var UnsortedTrees = ["spruce", "pine", "cedar"];
let ordered = document.createElement("ol");
domTarget("tree-display").appendChild(ordered);
UnsortedTrees.forEach(Unsortedtree => {
  let listOfTrees = document.createElement("li");
  ordered.appendChild(listOfTrees);
  listOfTrees.innerHTML += Unsortedtree;
});

const frontAdd = () => {
  console.log(UnsortedTrees);
  let userInput = domTarget("array-input").value;
  var isValid = true;
  if (userInput === "") {
    alert("Please enter a tree name");
    isValid = false;
  }
  if (userInput) {
    UnsortedTrees.push(userInput);
    domTarget("tree-display").reset();
    let ordered = document.createElement("ol");
    domTarget("tree-display").appendChild(ordered);
    UnsortedTrees.forEach(Unsortedtree => {
      let listOfTrees = document.createElement("li");
      ordered.appendChild(listOfTrees);
      listOfTrees.innerHTML += Unsortedtree;
    });
  }
};

window.onload = () => {
   domTarget("front-add").onclick = frontAdd;
};

1
  • If possible, could you add your html too to make a working snippet please? Commented Nov 1, 2019 at 8:23

2 Answers 2

1

Refactored your code a little bit. Would this be what you mean?

(() => {
  const byId = id => document.querySelector(`#${id}`);
  const ordered = byId("treeList");
  const appendListItem = (orderedList, itemTxt) => {
    let listItem = document.createElement("li");
    listItem.textContent = itemTxt;
    orderedList.appendChild(listItem);
  };
  const addItem = () => {
    const inputEl = byId("array-input");
    const val = inputEl.value.trim();
  
    if (!val) { return alert("Please enter a tree name"); }

    UnsortedTrees.push(val);
    appendListItem(ordered, val);
    inputEl.value = "";
  };
  
  // create initial
  let UnsortedTrees = ["spruce", "pine", "cedar"];
  UnsortedTrees.forEach(item => appendListItem(ordered, item));
    
  // add button handling
  byId("addItem").addEventListener("click", addItem);
})();
<div id="tree-display">
  <ol id="treeList"></ol>
</div>
<input id="array-input" type="text" placeholder="type a tree name"> 
<button id="addItem">Add</button>

Sign up to request clarification or add additional context in comments.

7 Comments

perfect...It worked, exactly what I wanted...I was actually thinking I could get it done with pure Js without using query selector, But I think this appears neater.
However, I would still like to know if this can be solved with pure JavaScript only and without using jQuery. Thanks
that is pure javascript ~ are you referring to the #${id} within backticks? That is a new(ish) method to use strings as variables and nothing to do with jQuery. It saves the need to escape from quotes to embed a variable
Hi @Codelate, glad I could help. FYI: all the scripting in the snippet is plain vanilla javascript (ES20xx). See: developer.mozilla.org/nl/docs/Web/API/Document/querySelector. Also: exploringjs.com/es6
@KooiInc, Now the coder runs well here but when I tried to implement it on VScode to the browser, it doesn't. I got the same issue. Result only flashed and never add up physically. I tried to debug and got a Reference error: "document is not defined". What could be the possible cause please. sorry for bothering you
|
0

I too did a little re-factoring ~ aka playing which might perhaps be of help/interest?!

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Trees in the Forest</title>
        <style>
            body, body *{ box-sizing:border-box;font-family:monospace }
            #forest{ width:100%; height:50vh;}
            .tree{
                width:50px;
                height:80px;
                margin:0.25rem; 
                background:url(https://png.pngtree.com/element_our/sm/20180527/sm_5b0b21833edb1.png);
                background-size:contain;
                background-repeat:no-repeat;
                background-position:bottom;
                background-color:rgba(0,200,0,0.1)
            }
            ol{ width:100%; margin:1rem auto }
            ol > li{display:inline-block;text-align:center}
        </style>
        <script>
            document.addEventListener('DOMContentLoaded',()=>{

                const domTarget=function(n){
                    return document.getElementById( n );
                };

                /* utility to generate new DOM elements with attributes and value */
                const create=function(t,a,p){
                    let el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
                    let _arr=['innerHTML','innerText','html','text'];
                    for( let x in a ) if( a.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, a[ x ] );
                    if( a.hasOwnProperty('innerHTML') || a.hasOwnProperty('html') ) el.innerHTML=a.innerHTML || a.html;
                    if( a.hasOwnProperty('innerText') || a.hasOwnProperty('text') ) el.innerText=a.innerText || a.text;
                    if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
                    return el;
                };

                /* wrapper for rebuilding the OL contents */
                const createforest=function(a,p){
                    p.innerHTML=''; // clear previous content
                    a.sort( ( x, y )=>{ return x > y ? 1 : -1 } ) // sort the array alphabetically
                    a.forEach( tree => { create( 'li',{ text:tree, 'class':'tree', 'data-tree':tree }, p ); } ); // add each tree
                };


                /* The initial collection of trees */
                let trees=[ 'spruce', 'pine', 'cedar' ];



                /* Existing DOM elements */
                let forest=domTarget('forest');
                let bttn=document.querySelector('form > input[ type="button" ]');
                let ol=create( 'ol', {}, forest );



                /* create the initial display of trees */
                createforest( trees, ol );




                /* Listen for button clicks - add new tree to the array and rebuild display */
                bttn.addEventListener( 'click', function(e){
                    let input=this.previousElementSibling;
                    if( input.value!='' ){
                        if( trees.length >= 3 ){
                            /* add to the array */
                            trees.push( input.value );

                            /* rebuild the display */
                            createforest( trees, ol );

                            /* clear the input field */
                            input.value='';
                            input.focus();
                        }
                        return true;
                    }
                    alert( 'Please enter a tree name' );
                });


                /* listenen for clicks on parent container */
                ol.addEventListener('click',(e)=>{
                    if( e.target!=e.currentTarget ){
                        /* remove tree from array and display */
                        let tree=e.target.dataset.tree;
                        trees.splice( trees.indexOf( tree ), 1 );
                        e.target.parentNode.removeChild( e.target );
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id='forest'></div>
        <form>
            <input type='text' />
            <input type='button' value='Add Tree' />
        </form>
    </body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.