I am currently building a shopping list app that contains a form, input box and submit button. My goal is to allow the user to input values into the form up until there has been 6 items listed on the page; after it has reached 6, I would like to disable the button so that no more values can be added. However, if a user deletes an item (e.g. the list goes down to 5 items), I would like for the button to be enabled until it reaches 6 and then continue the same routine over again.
I have tried to use an array and an "if else if statement" specifying the conditions, but that has not worked. Below is the JS code that I have tried.
let items = [];
let list = document.querySelector('ul');
let input = document.querySelector('input');
let button = document.querySelector('button').addEventListener('click', buttonClick);
function buttonClick() {
let myItem = input.value;
console.log(items)
items.push(input.value);
input.value = '';
if (items.length === 6) {
let e = document.querySelector('button').disabled = true;
items.length = 0;
} else if (button.disabled === false) {
button.disabled = true;
}
Here is the HTML
<img src='img/paper.jpg'>
<div class='second'>
<label for="item">Enter a new item:</label>
<input type="text" name="item" id="item">
<button>Add item</button>
</div>
<ul>
</ul>
</div>
I continue to receive an error message on the console stating, "Cannot read property disabled of undefined".
I think you should change this line of your code
let button = document.querySelector('button').addEventListener('click', buttonClick);
To this one
let button = document.querySelector('button');
button = .addEventListener('click', buttonClick);
And then you can make it disabled or not without selecting it again
button.disabled = true or button.disabled = false
Your need to get your button by id.
Change this:
let e = document.querySelector('button').disabled = true;
to this:
document.getElementById("ID_OF_BUTTON").disabled = true;
Remember to change "ID_OF_BUTTON" to id you put on your button html.
I think chaining the method in below code is causing the issue:
let button = document.querySelector('button').addEventListener('click', buttonClick);
Solution:
1.First get the button control:
let button=document.querySelector('button');
2.Attach event handlor.
button.addEventListener('click',buttonClick);
Related
basically I want to provide the user two options, Yes or No. For example, if he clicks the Yes button, then this information is saved and I can show what he chose at the end of the questionnaire.
I'm trying this way, but it's not working. At the end, nothing appears on the screen...
answer2-A = Yes Button
answer2-B = No Button
----------------------------//------------------------//-------------------------
document.getElementById('answer2-A').addEventListener("click", defineYes);
document.getElementById('answer2-B').addEventListener("click", defineNo);
};
function defineYes(){
document.getElementById('answer2-A').value = 'Yes';
document.getElementById('info').innerHTML = document.getElementById('answer2-A');
};
function defineNo(){
document.getElementById('answer2-B').value = 'No';
document.getElementById('info').innerHTML = document.getElementById('answer2-B');
Few things to address - without seeing the HTML I assume the value property isn't set on the buttons. Additionally you can/should get references to the buttons and re-use them instead of querying over and over. You can use the target of the event to access which button you clicked.
const yesBtn = document.getElementById('answer2-A')
const noBtn = document.getElementById('answer2-B')
const info = document.getElementById('info');
yesBtn.addEventListener("click", trackClick);
noBtn.addEventListener("click", trackClick);
function trackClick(e) {
info.innerHTML = e.target.value;
}
<button id="answer2-A" value="Yes">Yes</button>
<button id="answer2-B" value="No">No</button>
<div id="info"></div>
Program starts with displaying all notes from localstore, but when I click the addButton it display my current note only.
I want to show all the notes and after click event new note will add with previous notes.
let addButton = document.querySelector(".addBtn");
let userNotes = [];
displayNotes();
//addButton Event Listner
addButton.addEventListener("click", function(e) {
e.preventDefault();
//get the user inputs
let userInputs = {
title: document.getElementById("title_input").value,
description: document.getElementById("des_input").value
};
//push user inputs to arrays
userNotes.push(userInputs);
document.querySelector("form").reset();
//store to the localstorage
localStorage.setItem("Notes", JSON.stringify(userNotes));
//display to the user
displayNotes();
});
function displayNotes() {
let gettingNotes = localStorage.getItem("Notes");
let allNotes = JSON.parse(gettingNotes);
let html = "";
allNotes.forEach(element => {
html += `
<div class="single-item">
<h2 class="single-item-title">
${element.title}
</h2>
<p class="single-item-description">
${element.description}
</p>
</div>
`;
});
document.querySelector(".item-list").innerHTML = html;
}
It happens because you set userNotes to be an empty array and you add only your current note. Try to initialize userNotes with a value from localStorage, i.e
let userNotes = JSON.parse(localStorage.getItem('Notes')) || []
Also, then you are able to use userNotes variable in displayNotes function, instead of allNotes.
I have a form that has several radio groups. There is one particular radio group that I want the user to be able to reset without resetting the entire form. I created a button whose value is Reset Participation Levels. Here is the function for the click event of that button:
<script>
function ParticipationReset(){
document.getElementById('SponsorshipParticipaton_0').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_1').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_2').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_3').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_4').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_5').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_6').removeAttribute('disabled');
document.getElementById('ExhibitorParticipaton_0').removeAttribute('disabled');
document.getElementById('ExhibitorParticipaton_1').removeAttribute('disabled');
document.getElementById('SponsorshipParticipaton_0').checked = false;
document.getElementById('SponsorshipParticipaton_1').checked = false;
document.getElementById('SponsorshipParticipaton_2').checked = false;
document.getElementById('SponsorshipParticipaton_3').checked = false;
document.getElementById('SponsorshipParticipaton_4').checked = false;
document.getElementById('SponsorshipParticipaton_5').checked = false;
document.getElementById('SponsorshipParticipaton_6').checked = false;
document.getElementById('ExhibitorParticipaton_0').checked = false;
document.getElementById('ExhibitorParticipaton_1').checked = false;
}
</script>
However, when I click the button, all radio buttons in the form are reset even if they are not specified in the function. The link to the page is www.pfacmeeting.org/2016/exhibitorform.htm.
Any advice would be appreciated. Thank you
cdr6545
this is happening because the button is set as "reset" , for a particular reset, please change the line to:
<input type="button" name="ResetSponsor" id="ResetSponsor" value="Reset Sponsorship Participation" onclick="javascript:SponsorshipReset(this);" />
type="button"
You can reset all of the radio buttons in a group with a simple for loop like this:
var elements = document.getElementsByName("SponsorshipParticipation");
for(var i = 0; i < elements.length; i++) {
elements[i].removeAttribute("disabled");
elements[i].checked = false;
}
Or if you want to reset all radio button groups with a name ending in "Participation", you could change the first line to this:
var elements = document.querySelectorAll("input[name$='Participation']");
Here is an example of how you could implement the code I provided above:
HTML
<input type="button" value="Reset" onclick="resetParticipation()" />
JavaScript
function resetParticipation() {
var elements = document.querySelectorAll("input[name$='Participation']");
for(var i = 0; i < elements.length; i++) {
elements[i].removeAttribute("disabled");
elements[i].checked = false;
}
}
I have got a small javascript function and a piece of html code where i have a button, and I want that whenever user hovers that button, a little box to appear.Everything seems to be working great,despite that my function executes only after I hover that button for the 2 time(after the page has just loaded and I try to use my function for the 1 time, later everything executes after a firs hover).So what can I do about it?
HTML code
<body>
<div id = "searchBox">
<p id = "paragraph"><input type = "text" name = "serachBar"/>
<input type = "button" value = "szukaj" name = "search"/>
</p>
<div id = "searchButton">Szukaj</div>
</div>
</body>
and javascript itself
<script type = "text/javascript">
function popUp(menu){
var searchBox = document.getElementById(menu).style;
var searcButton = document.getElementById('searchButton');
if(!searchBox || searchBox.display == "none"){
searchBox.display = "block";
}
else {
searchBox.display = "none";
}
};
</script>
Change your if statement like this:
function popUp(menu) {
var searchBox = document.getElementById(menu);
var searcButton = document.getElementById('searchButton');
if (searchBox) {
if(searchBox.style.display == ""){
searchBox.style.display = "block";
}
else {
searchBox.style.display = "";
}
}
};
The original value will be "" instead of "none".
I'm making the assumption that the CSS setting is to display:"none".
I also moved the searchBox condition. If it isn't found, you don't want to set properties at all.
<p> is a flow element and can't contain <input>s.
Besides, your function instructs to toggle hidden state, rather than show box on mouseover. Therefore, the box will hide on first hover, and reappear on the second one.
You probably want to define mouseover and mouseout event listeners.
I am trying to limit the number of additional form input fields that a user can add dynamically to a file upload form to just 3. The form is loaded with one static input field and through javascript can add additional fields with an add button or remove additional form input fields with a remove button. Below is the html in it's static form.
<fieldset>
<legend>Upload your images</legend>
<ol id="add_images">
<li>
<input type="file" class="input" name="files[]" />
</li>
</ol>
<input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/>
</fieldset>
With javascript I would like to create a function where the number of child elements are counted and if the number is equal to three then the "Add Another Image" button becomes disabled. In addition, if there are three elements in the form the user - with the remove button - removes a child then the "Add Another Image" button becomes enabled again.
I think I'm may be missing some crucial lines of code. The below javascript code only allows me to add one additional input field before the Add Another Image button becomes disabled. Removing this field with the remove file button removes the field but the Add Another Image button is still disabled. Below is where I'm currently at with the javascript.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
}
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = nodelist.length;
for(i = 0; i < count; i++) {
if (nodelist[i] ==3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
}
}
Oh, OK, I've tested out the code now and see a couple of problems:
You're counting the number of child elements but this includes the text elements so there's actually one for the <li> and one for the text within it.
You've enclosed the true/false setting for the disabled property in quotes but it doesn't work and always set's it to false.
The remove button doesn't re-enable the add button.
I found this to work:
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
toggleButton();
}
toggleButton();
}
function toggleButton() {
var form = document.getElementById('add_images');
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = 0;
for(i = 0; i < nodelist.length; i++) {
if(nodelist[i].nodeType == 1) {
count++;
}
}
if (count >= 3) {
document.getElementById("addFile").disabled = true;
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = false;
}
}
I would suggest a slightly different approach. Create all three file input fields statically and provide a clear button. If the user chooses to leave it empty they can. If that is not elegant use your "Remove" to simply hide the field (CSS style display: none;).
I'm not sure why you're using the for loop? Shouldn't it be like this:
var nodelist = form.childNodes;
if (nodelist.length >= 3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
The last part of that function is a bit strange. Technically, when adding fields, you should only be disabling the button (i.e. you could never enable the button by adding fields). I would suggest removing the for loop and going with:
var count = form.getElementsByTagName("li").length;
if(count == 3)
document.getElementById("addFile").disabled = true;
The reason the add field button is still disabled when you remove an item is because you don't re-enable the add field button when you click remove. Try this for the remove button click handler:
rb.onclick = function () {
form.removeChild(this.parentNode);
document.getElementById("addFile").disabled = false;
}