changing value of element with a button - javascript

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" />

Related

How to make complete form in which background color of button changes when user starts typing in input field with javascript , html and css?

const btn = document.getElementById("btn");
const inputfield = document.getElementById("username");
inputfield.addEventListener("keyup", function(e) {
const val = e.target.value;
if (val === "") {
btn.disabled = true;
btn.style.backgroundColor = "grey";
} else {
btn.disabled = false;
btn.style.backgroundColor = "orange";
}
})
<div class="container">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
Now the issue is that it only works for one input and the associated button field
it does not work for another pair of input field and button , so what changes should i make in the above javascript code in which it runs for as many as input field and button i want?
Please can anyone help me in this. Thank you
If you have full jquery code it's also accepted.
My approach was to put the input and button in a div with a custom class.
And just loop over every div, get the child inputs and buttons and just use your existing code for every div.
const btns = document.getElementsByClassName('inputButton');
for (let i = 0; i < btns.length; i++) {
let input = btns[i].querySelector('input');
let button = btns[i].querySelector('button');
input.addEventListener("keyup", function(e) {
const val = e.target.value;
if (val === "") {
button.disabled = true;
button.style.backgroundColor = "grey";
} else {
button.disabled = false;
button.style.backgroundColor = "orange";
}
});
}
<div class="container">
<div class="inputButton">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="inputButton">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="inputButton">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
</div>
Just wrap it into a additional div element and iterate trough. For each "input-group" you can add an event listener to the input child and edit the style of the button child.
document.querySelectorAll('.input-group').forEach((group) => {
let input = group.querySelector('input');
let button = group.querySelector('button');
input.addEventListener('keyup', () => {
if(input.value !== "") {
button.disabled = false;
} else {
button.disabled = true;
}
});
});
#btn[disabled] {
background: red;
}
#btn {
background: green;
}
<div class="container">
<div class="input-group">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="input-group">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
<div class="input-group">
<input id="username" placeholder="Username" class="input" />
<button disabled id="btn" type="button" class="button">Submit</button>
</div>
</div>
You can make a loop with a class to add an event listener to every input you want.
You can use data-whateverYouWant to link the button to the input
Also, should make your style in css.
let inputs = document.getElementsByClassName("an-input");
for (let i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("keyup", function(e) {
let btn = document.querySelectorAll("[data-placeholder="+this.placeholder+"]")[0];
if (this.value === "") {
btn.disabled = true;
} else {
btn.disabled = false;
}
})
}
button{
background-color:orange;
}
button:disabled,
button[disabled]{
background-color:grey;
}
<input class="an-input" placeholder="Username" class="input" />
<button disabled data-placeholder="Username" type="button" class="button">Submit</button>
<input class="an-input" placeholder="email" class="input" />
<button disabled data-placeholder="email" type="button" class="button">Submit</button>

JavaScript function() for buttons disabled/enabled

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>

How to pass a value to a function and cont execute

I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem

Creating a dynamic form with input buttons

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.

onclick create textbox

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/

Categories