I have two buttons in my HTML:
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton()">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton2()" disabled="true">
</form>
I want to write a function() in JavaScript for when I click on button1 it should be disabled and change it's value to "not clickable" and button2 should be enabled and change it's value to "clickable" and the other way around.
I have written two functions but they aren't correct and I am very new to JavaScript. This is my functions():
function switcher() {
var btn = document.getElementById("knapp1");
btn.disabled = true;
}
function switcher2(){
var btn2 = document.getElementById("knapp2");
btn2.enabled = true;
}
You have a problem with the name of your function : switchButton() in your html and switcher in your js, the id are different too and enabled is not an html property. You can achieve what you want with only one function :
function switchButton(btn1, btn2) {
var btn1 = document.getElementById("button"+btn1);
var btn2 = document.getElementById("button"+btn2);
btn1.disabled = true;
btn1.value = "not clickable";
btn2.disabled = false;
btn2.value = "clickable";
}
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton(1,2)">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton(2,1)" disabled="true">
</form>
You should try to avoid have this duplicate logic that make the same, is very hard to maintain, I recommend to you instead use this:
function clickButton(e) {
const currentBtn = document.getElementById(e);
const otherBtn = document.getElementById(e === "knapp2"? "knapp1": "knapp2");
currentBtn.disabled = true;
otherBtn.disabled = false;
currentBtn.value="Not Clickable"
otherBtn.value="Clickable"
}
<form>
<input type="button" id="knapp1" value="Clickable" onClick="clickButton('knapp1')">
<input type="button" id="knapp2" value="Not Clickable" onClick="clickButton('knapp2')" disabled>
</form>
Related
I have a basket of goods in which there can be many different entities. And I'm trying to implement changes in the number of goods using input - number without arrows, and with additional buttons +/-. I know that I could use identifiers and easily make my plans. But in my case, I need to use querySelectorAll. Help me please correct this code. quantity-arrow-minus decreases the field value and quantity-arrow-plus increases. How to make it so that the changes are concerned with each item?
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
node.addEventListener('click', function() {
update_cart.forEach(function(element) {
element.value = parseInt(element.value) - 1;
});
});
});
plus.forEach(function(node) {
node.addEventListener('click', function() {
update_cart.forEach(function(element) {
element.value = parseInt(element.value) + 1;
});
});
});
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
<form method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
You can use previousElementSibling and nextElementSibling to access the input that corresponds to the button that was clicked:
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
node.addEventListener('click', function(e) {
const input = e.target.nextElementSibling
input.value = parseInt(input.value) - 1;
});
});
plus.forEach(function(node) {
node.addEventListener('click', function(e) {
const input = e.target.previousElementSibling
input.value = parseInt(input.value) + 1;
});
});
<form action="{% url 'cart:cart_update' %}" method="GET">
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="0">
<button type="button" class="quantity-arrow-plus">+</button>
<br>
<button type="button" class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="0">
<button type="button" class="quantity-arrow-plus">+</button>
</form>
Use Number() instead. Assuming that the minus button will be just after your input, just use this.nextElementSibling. This is will make your code better instead of doing forEach on every element. What if there are many elements like these?
var minus = document.querySelectorAll('.quantity-arrow-minus');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach((node) => {
node.onclick = function () {
this.nextElementSibling.value = Number(this.nextElementSibling.value) - 1;
}
});
plus.forEach((node) => {
node.onclick = function () {
this.previousElementSibling.value =Number(this.previousElementSibling.value) + 1;
}
});
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
<br>
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
<br>
<button class="quantity-arrow-minus">-</button>
<input type="number" class="update_cart" value="1">
<button class="quantity-arrow-plus">+</button>
I am trying to disable/enable an input line by clicking a button
I can manually enter the word "closed" in an input line and it works fine, but I can not get the "closed" to get entered with a button
var obj = document.getElementById("state");
obj.onchange = function(status){
if(this.value=="closed"){
document.getElementById("test").disabled = 'disabled';
}else{
document.getElementById("test").disabled = '';
}
}
<button id="state" name="state" type="submit" value="open">open</button>
<button id="state" name="state" type="submit" value="closed">closed</button>
<input id="test"/>
The input id=state line works fine, but nothing happens when I click the buttons
There is a few things to consider :
You can’t use multiple times the same ID (state)
A button won’t react to a onChange, but a onClick
You can directly use the onClick HTML attribute
function disableInput(disabled){
document.getElementById("test").disabled = disabled
}
<button onClick="disableInput(false)">open</button>
<button onClick="disableInput(true)">closed</button>
<input id="test" />
Perhaps you want a toggle?
window.addEventListener("load", function() {
document.getElementById("state").addEventListener("click", function(e) {
e.preventDefault(); // not really needed on type="button"
var closed = this.value == "closed";
this.value = this.innerText = closed ? "open" : "closed";
document.getElementById("test").disabled = closed;
})
})
<button id="state" name="state" type="button" value="open">open</button>
<input id="test" />
Try something like this,
var buttonClick = function(status) {
if (status == "closed") {
document.getElementById("test").disabled = true;
} else {
document.getElementById("test").disabled = false;
}
}
<button id="openState" name="OpenState" type="submit" value="open" onclick="buttonClick(value)">open</button>
<button id="closedState" name="ClosedState" type="submit" value="closed" onclick="buttonClick(value)">closed</button>
<input id="test" />
I have a form with tabs which include buttons. Before the user clicks next, I want to check if at least one or all the buttons have been clicked, if clicked, the next tab shows up. If not, an alert pops up!
<button class="btns rem" id="mon">morning</button>
<button class="btns rem" id="oo" >afternoon</button>
<button class="btns rem" id="pp" >night</button>
<button class="btns" id="day" >Next</button>
<script type="text/javascript" >
document.getElementById("day").onclick =
function(event) {
var btn=
document.getElementsByClassName("btns") ;
for(x=0; x<btn.length; x++){
if(btn[x].click == true){
prompt("open Next page?");
}
else {
alert("please click at least one button");
}
}
</script>
Better way of doing it is to use checkboxes since you want to check if at least one or all the buttons have been clicked. Then attach the onchange event.
var btns = document.getElementsByClassName("radio-btn") ;
var len = btns.length;
var isSelected = false;
while(len--) {
btns[len].onchange = function() {
isSelected = this.checked ? true : false;
};
}
document.getElementById("day").onclick = function() {
if(isSelected) {
alert("open Next page?");
}
else {
alert("please click at least one button");
}
}
<form onsubmit="return false;">
<input type="checkbox" name="time" class="radio-btn rem"> Morning<br>
<input type="checkbox" name="time" class="radio-btn rem"> Afternoon<br>
<input type="checkbox" name="time" class="radio-btn rem"> Evening<br>
<button class="btns" id="day" >Next</button>
</form>
If you like just try it.
<button class="btns rem" id="mon">morning</button>
<button class="btns rem" id="oo" >afternoon</button>
<button class="btns rem" id="pp" >night</button>
<button class="btns" id="day" >Next</button>
<script type="text/javascript" >
var clickedData = "";
function setClicked(data){
clickedData = data;
}
var btn = document.getElementsByClassName("btns");
for(x = 0 ; x < btn.length; x++){
if(btn[x].id !=="day"){
const val = btn[x].innerHTML;
btn[x].onclick = function(){ setClicked(val); }
}
}
document.getElementById("day").onclick =
function(event) {
if (clickedData !== ""){
prompt("open Next page?");
}else{
alert("please click at least one button");
}
}
</script>
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
this is a dumb question but for some reason i can't figure it out or find a simple example anywhere. all i want is a button that when clicked, creates a textbox with the same name +1.
<input type="button" value="Show" onclick="blah" />
<!-- Button Gets Clicked -->
<input type="text" name="added1" />
<!-- Button Gets Clicked -->
<input type="text" name="added2" />
<!-- Button Gets Clicked -->
<input type="text" name="added3" />
maybe javascript!? any ideas?
Inline javascript is not the best way to approach this, but...
<input type="button" value="Show" onclick="var e = document.createElement('input'); e.type='text'; e.name = 'added'+this.rel; this.rel = parseFloat(this.rel)+1; this.parentNode.appendChild(e); return false;" />
Better to separate your presentation from your script:
HTML:
<input type="button" value="Show" id="add_btn" />
Cross-browser Javascript:
var handler_func = function () {
var i = (typeof this.rel != 'undefined') && (this.rel - 0) == this.rel ? this.rel : 0;
var e = document.createElement('input');
e.type='text';
e.name = 'added'+i;
this.rel = i+1;
this.parentNode.appendChild(e);
return false;
}
var add_btn = document.getElementById('add_btn');
if(add_btn.attachEvent)
add_btn.attachEvent('onClick', handler_func);
else if(add_btn.addEventListener) //Firefox & company
add_btn.addEventListener('click', handler_func, false);
Fiddle: http://jsfiddle.net/rkYpD/1/