getElementsByName Example

by j_mc_falcon_19

HTML

<main></main>
  <div class="container">
     <div class="row">
        <span>Total Options: </span>
        <span class="box" id="count" ></span>
     </div>
     <div class="row">
        <div id="surveyitems">
           <button name="survey" >JS Rocks</button>
           <button name="survey" >JS Doesn't Rock</button>
           <button name="survey" >I don't know what JS is</button>
        </div>
     </div>
     <div class="row">
        <div>
           <input id='surveyinput' placeholder="Enter Survey Item" />
           <button onclick="AddNewSurveyItem()" >Add New Item </button>
        </div>
     </div>
  </div>
</main>

CSS

main {
	background-color: #9e9e9e00;
}

.container {
	flex-direction: column;
	display: flex;
}

.row {
	align-items: center;
	justify-content: space-evenly;
	padding: 20px;
	margin: 10px;
	width: 500px;
	height: 100px;
	border-radius: 3px;
	background-color: white;
	box-shadow: black;
	-webkit-box-shadow: 1px 1px 6px 1px #000000;
	box-shadow: 1px 1px 6px 1px #000000;
	display: flex;
	flex-direction: row;
}

.box {
	padding: 10px;
	background-color: coral;
	color: white;
	border-radius: 5px;
	;
}

JavaScript

var surveylist;



window.onload = function() {

    debugger

    //Assign the elements to variable

    surveylist = document.getElementsByName('survey');



    // Update the Count Display

    UpdateDisplay()

}



function AddNewSurveyItem() {

    debugger

    let container = document.getElementById('surveyitems');

    let input = document.getElementById('surveyinput');

    if (input.value.length > 0) {

        let element = document.createElement('button');

        element.textContent = input.value;

        element.name = 'survey';

        container.appendChild(element);



        UpdateDisplay();

    }

}



function UpdateDisplay() {

    document.getElementById('count').innerText = surveylist.length;

}