I have a button with a var that start with a 0 and when you click a another button it increases to 1. But if you click the second button first, the var goes negative. The button is disabled at the beginning, but when it increases to 1 the button should be enabled.
When the page is loaded the button disabled, but when the var goes to 1 the button is still disabled.
I tried: if(var == 0){document.getElementById("button1").disabled = true; return false;}
You can do something like in below snippet :
You can use any tag instead of input like div span h1 ... which ever you wish and style according to need .
This thing you will need to change will be change .value to .innerHTML everywhere like this(1 example) :
var units = document.getElementsByClassName("unitsMain")[0].innerHTML
function decreaseUnits() {
var units = document.getElementsByClassName("unitsMain")[0].value
if (units > 0) {
units--;
document.getElementsByClassName("unitsMain")[0].value = units;
}
}
function increaseUnits() {
var units = document.getElementsByClassName("unitsMain")[0].value
units++;
document.getElementsByClassName("unitsMain")[0].value = units;
}
<button class="decOrderUnits" onclick="decreaseUnits()"><i class="fa fa-minus"></i>-</button>
<input class="unitsMain" value="0" maxlength="3">
<button class="incOrderUnits" onclick="increaseUnits()"><i class="fa fa-plus"></i>+</button>
Related
The Problem:
I can't seem to be able to get a list of buttons to change the value of their corresponding inputs.
I'm trying to code a cart system for my website, pretty standard. It involves a list of item, each of which have a section that includes two buttons for adding or subtracting the quantity of its corresponding item. These buttons surround the input that displays the current quantity (disabled so that the user must use the buttons to control it).
Everything is working, but I can't seem to figure out how to target the corresponding input of a button that is clicked so that it will change the value of that specific input.
What I've Tried:
I've figured out that if I add a [0] at the end of the "quantityInputs" variable then it will target the first input in the list, makes sense. But I don't want it to only target the first input, I want it to target the input that the button is associated with. Even then, when I test the plus button it only updates the input one time to 2 and then stops, which I only know because I'm printing the value to the console - it doesn't actually change the display on the webpage.
I've considered using a for loop to get the position of the input, but I'm not sure how to incorporate that into the code in order for it to work with the for loop that gets the position of the plus or minus buttons, or if that will even work.
Can anyone please help me out? I'd really appreciate it.
My Code:
HTML:
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
changeQuantity()
}
function changeQuantity() {
var buttonUps = document.getElementsByClassName('item-quantity-up')
console.log('There are ' + buttonUps.length + ' plus buttons total.') // Tells you how many plus buttons there are.
for (var i = 0; i < buttonUps.length; i++) { // Get the positions of each plus button.
var button = buttonUps[i]
button.addEventListener('click', addQuantity) // When a plus button is clicked, run the addQuantity function.
}
var buttonDowns = document.getElementsByClassName('item-quantity-down')
console.log('There are ' + buttonDowns.length + ' minus buttons total.') // Tells you how many minus buttons there are.
for (var i = 0; i < buttonDowns.length; i++) { // Get the positions of each minus button.
var button = buttonDowns[i]
button.addEventListener('click', subQuantity) // When a minus button is clicked, run the subQuantity function.
}
}
function addQuantity(event) {
var quantityInputs = document.getElementsByClassName('cart-item-quantity') // Needs an index such as [0] in order to return a real number.
var inputValue = parseInt(quantityInputs.value) // Turns the value into an integer.
var max = quantityInputs.max // Retrieves the max value for the input.
if (inputValue >= max) {
inputValue = inputValue // If the quantity is greater than or equal to the max, then don't change the quantity.
} else {
inputValue = inputValue + 1 // If the quantity is less than the max, then add 1 to the quantity.
console.log(inputValue)
}
}
function subQuantity(event) {
var quantityInputs = document.getElementsByClassName('cart-item-quantity') // Needs an index such as [0] in order to return a real number.
var inputValue = parseInt(quantityInputs.value) // Turns the value into an integer.
var min = quantityInputs.min // Retrieves the min value for the input.
if (inputValue <= min) {
inputValue = inputValue // If the quantity is less than or equal to the min, then don't change the quantity.
} else {
inputValue = inputValue - 1 // If the quantity is greater than the min, then subtract one from the quantity.
console.log(inputValue)
}
}
<div class="cart-quantity-field">
<button class="item-quantity-down">-</button>
<input class="cart-item-quantity" type="number" min="1" max="20" value="1" disabled>
<button class="item-quantity-up">+</button>
</div>
You can manipulate the correct input field by doing the following:
On quantity-button click:
locate the clicked button's parent element
inside that parent, look for input with the correct class name
decide whether the button clicked should add or subtract one
add +1 or -1 respectively to the current value of the input
const allQuantityBtns = document.getElementsByClassName("quantity-btn");
Array.from(allQuantityBtns).forEach(btn => {
btn.addEventListener("click", e => {
const inputToChange = e.target.parentElement.querySelector(".cart-item-quantity");
const plusOrMinusOne = e.target.classList.contains("item-quantity-up") ? 1 : -1;
const newValue = parseInt(inputToChange.value) + plusOrMinusOne;
// validate newValue here. Eg: is it allowed to be smaller than zero?
inputToChange.value = newValue;
});
});
<div class="cart-quantity-field">
<button class="item-quantity-down quantity-btn">-</button>
<input class="cart-item-quantity" type="number" min="1" max="20" value="1" disabled>
<button class="item-quantity-up quantity-btn">+</button>
</div>
Note: you may wish to implement some validation:
stop the quantity from being too large or small before modifying the input's value
My HTML looks a like this for the specific button:
<h1 class = "counter">0</h1>
<button class="btn" type = "button" id = "lowerCountBtn" disabled>Lower Count</button>
In the Javascript, I have made a const variable used query selector to call the HTML element button. Counter was also made into a variable from a class on the HTML code.
My desire is for the disabled button to become an active button once the counter i have made following a tutorial, increase from 0. And when it returns to 0, the button in questions becomes disabled again.
The github link to the code is as follows:
https://github.com/Abdullah-Ijaz/Counter
JAVASCRIPT:
let counter = document.querySelector('.counter');
const button = document.querySelector('button');
function ableButton(){
if (counter.innerHTML === 0) {
button.disabled = true;
}
else if (counter.innerHTML > 0) {
button.disabled = false;
}
}
I see the function has been made but I assume I am just not calling the function somehow or the other. I really appreciate the help.
You can call your function inside of both your incrementCounter and decrementCounter functions after the rest of the logic.
Also, your conditions in those 2 functions are comparing strings against '0'.
Why not use the count variable and compare numbers if (count > 0) etc
When the user visits the page, this HTML text must display.
<p id="exampleText">Hit The "Change Text" Button Below To Change <span id="thisText"><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
After clicking this button:
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
Display This Text:
var txtExmp1 = "Hooooooooooooraayy!!, You Clicked and Changed The Text..." + "<br><br><br>" + "but now you have to fix me so i can change again";
Now user should be able to click the button and see previous text and back to the "Hooray" message in var txtExmp1.
I've tried to use an if statement but didnt work. Here's the code:
var defaultText = document.getElementById("exampleText");
if (defaultTex.innerHTML === defaultText){
defaultText.innerHTML = txtExmp1;
}
else {
defaultText.innerHTML = defaultText;
}
How can I make this texts toggle between each other considering one is html and the other is javascript. What is the simple and most effective way to toggle this texts?
Heres what it looks like (Screenshot image):
i.Before Click
ii.After click, but wont change again
This is relatively simple, when changing the text you need to take the current visible one and save it in a variable, then show the other stored text you have in txtExmp1 then when the use click again you take the other visible text store it and show the one you stored before, doing it this is highly inefficient.
From the start you store both strings in variables or array then toggle between them.
Of course this is just one way to achieve this.
let text = ["Hooooooooooooraayy!!, You Clicked and Changed The Text... <br><br><br>but now you have to fix me so i can change again", "Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works "];
let index = 0;
function textChanger() {
// Get the p Element refrence so we can modify it
var pElement = document.getElementById("exampleText");
// text[index] will return one of the texts from the array
// depening on the index if 0 its the first one
// if 1 it's the second one
// that's why we're altering index's value after every change
if (index == 0) {
pElement.innerHTML = text[index];
index = 1;
} else if (index == 1) {
pElement.innerHTML = text[index];
index = 0;
}
}
<p id="exampleText">Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
The word you are searching is toggle. Try switch case:
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementById("exampleText");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
toggleMe.textContent = "Hooooooooooooraayy";
break;
case "off":
toggleMe.toggleStatus="on";
toggleMe.textContent = " Hit The Change Text Button Below To change...";
break;
}
Good luck!
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;
}