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/
Related
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 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>
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.
I want to be able to add multiple rows to a div and also removing them. I have a '+' button at the top of the page which is for adding content. Then to the right of every row there is a '-' button that's for removing that very row. I just can't figure out the javascript code in this example.
This is my basic HTML structure:
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
This is what I want to add inside the content div:
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow()">
You can do something like this.
function addRow() {
const div = document.createElement('div');
div.className = 'row';
div.innerHTML = `
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label>
<input type="checkbox" name="check" value="1" /> Checked?
</label>
<input type="button" value="-" onclick="removeRow(this)" />
`;
document.getElementById('content').appendChild(div);
}
function removeRow(input) {
document.getElementById('content').removeChild(input.parentNode);
}
To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).
So using it you would write
function addRow () {
document.querySelector('#content').insertAdjacentHTML(
'afterbegin',
`<div class="row">
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function removeRow (input) {
input.parentNode.remove()
}
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
Another solution is to use getDocumentById and insertAdjacentHTML.
Code:
function addRow() {
const div = document.getElementById('content');
div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');
}
Check here, for more details:
Element.insertAdjacentHTML()
I know it took too long, it means you can write more briefly.
function addRow() {
var inputName, inputValue, label, checkBox, checked, inputDecrease, content, Ptag;
// div
content = document.getElementById('content');
// P tag
Ptag = document.createElement('p');
// first input
inputName = document.createElement('input');
inputName.type = 'text';
inputName.name = 'name';
// Second input
inputValue = document.createElement('input');
inputValue.type = 'text';
inputValue.name = 'Value';
// Label
label = document.createElement('label');
// checkBox
checkBox = document.createElement('input');
checkBox.type = 'checkbox';
checkBox.name = 'check';
checkBox.value = '1';
// Checked?
checked = document.createTextNode('Checked?');
// inputDecrease
inputDecrease = document.createElement('input');
inputDecrease.type = 'button';
inputDecrease.value = '-';
inputDecrease.setAttribute('onclick', 'removeRow(this)')
// Put in each other
label.appendChild(checkBox);
label.appendChild(checked);
Ptag.appendChild(inputName);
Ptag.appendChild(inputValue);
Ptag.appendChild(label);
Ptag.appendChild(inputDecrease);
content.appendChild(Ptag);
}
function removeRow(input) {
input.parentNode.remove()
}
* {
margin: 3px 5px;
}
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
You can use this function to add an child to a DOM element.
function addElement(parentId, elementTag, elementId, html)
{
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId)
{
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
To remove node you can try this solution it helped me.
var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);
Add HTML inside div using JavaScript
Syntax:
element.innerHTML += "additional HTML code"
or
element.innerHTML = element.innerHTML + "additional HTML code"
Remove HTML inside div using JavaScript
elementChild.remove();
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
<!DOCTYPE html>
<html>
<head>
<title>Dynamical Add/Remove Text Box</title>
<script language="javascript">
localStorage.i = Number(1);
function myevent(action)
{
var i = Number(localStorage.i);
var div = document.createElement('div');
if(action.id == "add")
{
localStorage.i = Number(localStorage.i) + Number(1);
var id = i;
div.id = id;
div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';
document.getElementById('AddDel').appendChild(div);
}
else
{
var element = document.getElementById(action.id);
element.parentNode.removeChild(element);
}
}
</script>
</head>
<body>
<fieldset>
<legend>Dynamical Add / Remove Text Box</legend>
<form>
<div id="AddDel">
Default TextBox:
<input type="text" name="default_tb">
<input type="button" id="add" onclick="myevent(this)" value="Add" />
</div>
<input type="button" type="submit" value="Submit Data" />
</form>
</fieldset>
</body>
</html>
I have a form like this:
<form action="#contact-form" method="post" class="th_contact-form" id="id-59907491">
<div class="form_line">
<label for="widget-2-your-email" class="th-field-label email" style="display:none;">Your Email<span>(required)</span></label>
<input type="text" name="widget-2-your-email" id="widget-2-your-email" placeholder="Your Email" class="email">
</div>
<div class="th_contact-submit">
<input type="submit" value="submit" class="th_button">
</div>
I want to change the value="submit" to say value="click here"
How do I do that using javascript? I do not have the liberty of changing the form code as it is auto-generated via a theme in wordpress, and they don't have the option of changing the button text.
Fastest way: document.querySelector("#id-59907491 [type=submit]").value = "click here";
Most stable way:
var frm = document.getElementById('id-59907491'),
inp = frm.getElementsByTagName('input'),
l = inp.length, i;
for(i=0;i<l;i++) {
if( inp[i].type == "submit") {
inp[i].value = "click here";
break;
}
}
Assuming there is only one button with the th_button class:
window.onload = function () {
var button = document.getElementsByClassName( 'th_button' )[0];
button.value = "Click Here";
};