JavaScript generate new input field on click - javascript

I am in the process of making an HTML form where users have different options. I am trying to make a button that infinitely generates a new set op input fields with increasements in the name, like:
The first generated input should have a name of input1. The next with a name of input2 and so on.
Here is a visual example: https://webmshare.com/ZBvw0
How can this be accomplished?

You can solve this problem by creating your form elements dynamically and appending them to your form element.
Below a simplified example, just to show the main idea.
Main points here are:
Document.createElement() - Which creates a specified HTML element (your form elements in this instance).
Node.appendChild() - Which adds a node to the end of the list of children of a specified parent node (your form element in this instance).
(function() {
var counter = 0;
var btn = document.getElementById('btn');
var form = document.getElementById('form');
var addInput = function() {
counter++;
var input = document.createElement("input");
input.id = 'input-' + counter;
input.type = 'text';
input.name = 'name';
input.placeholder = 'Input number ' + counter;
form.appendChild(input);
};
btn.addEventListener('click', function() {
addInput();
}.bind(this));
})();
input{
display: block;
}
<form id="form" action="">
</form>
<button id="btn" type="button">Click Me!</button>

You can use jquery to fetch the name of the last item.
Then you can use the javascript string replace method and replace 'input' with '' in order to get the number of the last item.
Then just increment it by 1. You will have to parse it as an integer before adding 1 to it.
Then with the incremented number, create a new input field and append it to your container.

Try this
HTML
<div id="demo">
</div>
<input type="button" id="add" value="Add input"/>
Javascript
var num = 1;
document.getElementById('add').addEventListener("click",addInput);
function addInput(){
var demo = document.getElementById('demo');
demo.insertAdjacentHTML('beforeend','<div class="form-holder" style="width: 30%;"><a class="form-label">Billet type</a> <br><select name="ttype'+num+'"><option value="normal">Standard Billet</option><option value="add-on">Tilkøbs Billet</option></select></div><div class="form-holder" style="width: 31%; margin-left: 0.6%;"><a class="form-label">Billet navn</a> <br><input name="tname'+num+'" type="text" placeholder="F.eks. Entré Billet" style="width: 100%;" /></div><div class="form-holder" style="float: right; width: 18%; margin-left: 1%;"><a class="form-label">Antal</a> <br><input name="tquan'+num+'" type="text" placeholder="F.eks. 500" style="width: 100%;" /></div><div class="form-holder" style="float: right; width: 18%;"><a class="form-label">Pris (DKK)</a> <br><input name="tprice'+num+'" type="text" placeholder="F.eks. 100" style="width: 100%;" /></div> <br>');
num++;
}
Check out jsFiddle example

Related

How do I write an html form of variable length to a plain text file?

I am somewhat new to the world of website design. I have an HTML form that consists of a dropdown box and an input box. I also have a button that creates move dropdown boxes and input boxes. There is not a limit on how many the user can create.
Once the user has put all of their desired input in, I want to take the entire form and write it to a plain text file (this will be used in a Python script). How can I do this without using a php form? Any input would be helpful. Thanks!
HTML form:
<form>
<table id = "actions_table" style="position: absolute; left: 486px; top: 25px">
<tr>
<td><select name = "action" id = "action" style="width: 108px;">
<option value = "Click_button">Click Button</option>
<option value = "Input_search">Input Search</option>
</select></td>
<td><input type = "text" style="width:100px" name = "input_text"></td>
</tr>
</table>
<input type = "submit" value="Add to Scrape" style="position: absolute; left: 720px; top: 150px; width:100px">
</form>
Add to form button:
<button type = "button" onclick="addAction()" style="position:absolute; left: 1050px; top: 125px;">Add Action</button>
Action behind Add to form button:
<script>
function addAction(){
//Get table
var action_table = document.getElementById("actions_table");
//Add selection box
var new_input_option = document.createElement("select");
new_input_option.style.width = "108px";
//Add option for click button
var click_opt = document.createElement("option")
click_opt.text = "Click Button"
//Add option for input search
var input_opt = document.createElement("option")
input_opt.text = "Input Search"
//add options
new_input_option.add(click_opt)
new_input_option.add(input_opt)
//Create new input box
var input_box = document.createElement("input")
input_box.style.width = "100px"
//Insert new row below last one
let newRow = action_table.insertRow(-1)
let newCell = newRow.insertCell(0)
let newCell2 = newRow.insertCell(1)
//Add stuff
newCell.appendChild(new_input_option);
newCell2.appendChild(input_box);
}
</script>
I have found ways to write designated form fields by the name of the field, but I just have not been able to simply get all elements from the form and write them to a plain text file. Thanks again for any input!

How do I select the last character of a string, using JavaScript?

I have a function that gets the last character of a string the user types in an input. But how do I select that single character, using execCommand()? The goal is to copy it into a different input.
I tried element.select(), but with no results.
The character to paste into the new input must be the character visible in the original input, and not the character correspondent to the keyboard key the user types, since the reason for all this is having an external JS library handling some CJK character conversion in one input, and moving the result to a different one..
I am going with a copy-paste approach. Hence, the need to select the character. But if there is a better way to achieve it, feel free to tell me about it.
I am open to both Vanilla JavaScript and jQuery approaches.
This is my code:
JSFiddle
function copyPaste () {
var i1 = document.getElementById('userInput');
var i2 = document.getElementById('input2');
var c = i1.value.substr(lol.length - 1);
c.select();
document.execCommand('copy');
i2.focus();
document.execCommand('paste');
i1.focus();
}
input {
width: 255px;
}
button {
display: block;
margin: 20px 0;
text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button" onclick="copyPaste"();>Then, click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">
You should not use execCommand as it is obsolete. Moreover, you don't need to use the clipboard to transfer a (part of a) string to another input box. This can be done with standard string handling:
You can use slice(-1) to get the final character.
I would also prefer addEventListener instead of the onclick attribute (where you had a typo also).
With += you can append the extracted character:
var input = document.getElementById('userInput');
var output = document.getElementById('input2');
var btn = document.querySelector('button');
btn.addEventListener("click", function () {
output.value += input.value.slice(-1);
});
input {
width: 255px;
}
button {
display: block;
margin: 20px 0;
text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button">Then, click here</button>
<input type="text" id="input2" value="Some text...">
The following worked for me:
html:
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button" onclick="copyPaste()";>Then, click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">
js:
function copyPaste () {
var i1 = document.getElementById('userInput');
var i2 = document.getElementById('input2');
var c = i1.value.slice(i1.value.length - 1);
i2.value = c;
}
Used slice() to get the last character of the string. Note I also fixed the onclick handler in your html.

Clicking a button and getting the input from a user

Here is a picture. I have done css and html on my own and now don't know how to add javascript here.
What I want is:
a user writes something
then he clicks on button (for example uppercase) and his text appears at the bottom, instead of words "Here will be you text". How can I add such a function? I am confused.
If you want it in pure Javascript, you can do the code in the snippet.
I will assume that you know HTML and CSS, end explains only the javascript code.
The idea is:
You attach an event listener to handle de user click in each button. Each button has it's own class name, you can use it as a parameter of the document.getElementsByClassName to get an array of objects with this class name. Next you attach the event handler, you can do this with addEventListener.
Inside the click event function, you put the action that will be triggered after any click at the button.
The snippet below has commented code to clear things.
//Get input field with text before any operation
var textField = document.getElementsByClassName("text-field")[0];
//Get button that will trigger the Upper Case function
var upperBtn = document.getElementsByClassName("to-upper-btn")[0];
//Get button that will trigger the Lower Case function
var lowerBtn = document.getElementsByClassName("to-lower-btn")[0];
//Get div that will show the result
var resultContainer = document.getElementsByClassName("text-result")[0];
//Attach a click event listener to the Upper Case button
upperBtn.addEventListener("click", function(){
//Set the inner html of the result container with te value of the input field in uppercase;
resultContainer.innerHTML = textField.value.toUpperCase();
});
//Attach a click event listener to the Lower Case button
document.getElementsByClassName("to-lower-btn")[0].addEventListener("click", function(){
//Set the inner html of the result container with te value of the input field in lowecase;
resultContainer.innerHTML = textField.value.toLowerCase();
});
.text-field {
width:300px;
}
.container {
margin-top:50px;
border:1px solid #e4e4e4;
border-radius:5px;
background:#000;
color:#FFF;
padding:10px;
}
<h1>Write something</h1>
<input type="text" class="text-field"/>
<button type="button" class="to-upper-btn">To Upper Case</button>
<button type="button" class="to-lower-btn">To Lower Case</button>
<div class="container">
<div class="text-result">Just write what you want to make Upper Case or Lower Case, the result will be displayer here</div>
</div>
For more details about the javascript methods used in this code:
getElementByClassName
addEventListener
toUpperCase
toLowerCase
The combination of onclick, toUpperCase and toLowerCase can be used to obtain the required result.
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<h2>Write something</h2>
<input id="inputText" type="text" placeholder="write something" style="width: 300px;">
<br>
<button onclick="upperCaseButtonClicked()">Upper case</button>
<button onclick="lowerCaseButtonClicked()">Lower case</button>
<button onclick="doNothingButtonClicked()">Do nothing</button>
<br>
<textarea id="outputArea" rows="5" cols="35"></textarea>
<script>
function upperCaseButtonClicked() {
var input = document.getElementById("inputText").value
var output = input.toUpperCase()
document.getElementById("outputArea").innerHTML = input.toUpperCase()
}
function lowerCaseButtonClicked() {
var input = document.getElementById("inputText").value
var output = input.toUpperCase()
document.getElementById("outputArea").innerHTML = input.toLowerCase()
}
function doNothingButtonClicked() {
var input = document.getElementById("inputText").value
document.getElementById("outputArea").innerHTML = input
}
</script>
</body>
</html>
const nameNode = document.getElementById("Name");
const nameCopyNode = document.getElementById("NameCopy");
if(nameNode){
nameNode.addEventListener('input',function(){
if(nameCopyNode){
nameCopyNode.value = this.value
}
})
}
<input type = "text" placeholder = "type your name" id="Name"/>
<br>
<br>
<input type = "text" placeholder = "you are typing" disabled id="NameCopy"/>
In the simplest form, using jQuery:
$(document).ready(function() {
$('#uppercase-btn').click(function() {
$('#myoutput').val($("#textid").val().toUpperCase());
});
$('#lowercase-btn').click(function() {
$('#myoutput').val($("#textid").val().toLowerCase());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="myinput" id="textid" />
<button id="uppercase-btn">Uppercase</button>
<button id="lowercase-btn">lowercase</button>
<textarea id="myoutput" disabled></textarea>

Removing Checked checkbox elements using a function

Trying to make a to-do list using JavaScript but can't seem to figure out a way to delete the checked checkboxes.
I tried to have the program change the id then delete everything with that new id but that didn't seem to work, maybe I was missing something important not sure but if any of you know a different way of deleting checked checkboxes, I'd appreciate the help.
function add() {
var myDiv = document.getElementById("myDiv");
var inputValue = document.getElementById("myInput").value;
// creating checkbox element
var checkbox = document.createElement('input');
if (inputValue === '') {
alert("Input is Empty!");
} else {
document.getElementById("myUL").appendChild(checkbox);
}
// Assigning the attributes to created checkbox
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "checkBox";
// create label for checkbox
var label = document.createElement('label');
// assigning attributes for the created label tag
label.htmlFor = "checkBox";
// appending the created text to the created label tag
label.appendChild(document.createTextNode(inputValue));
// appending the checkbox and label to div
myDiv.appendChild(checkbox);
myDiv.appendChild(label);
}
function remove() {
var doc = document.getElementById("checkBox").checked;
doc.remove;
}
<h1>To Do List</h1>
<input type="text" id="myInput">
<button onclick='add()'>Click me!</button>
<button onclick="remove()">Delete</button>
<ul id="myUL">
<div id="myDiv"></div>
</ul>
There are several issues to your code:
You are recycling the #checkBox ID. Remember that IDs must be unique within a document. Therefore, you should be generating a unique ID for each label + checkbox pair
You are only removing the checkbox element and not the label text, so even if your logic works, the appearance / outcome of your code is not what you want.
A solution will be wrapping your label text and the checkbox element inside the label. The advantages of this is that:
The <label> element does not need a for attribute, since clicking on the label will automatically check the nested checkbox
You can use .closest('label') to remove the entire label text + checkbox pair, when you hit the delete button
In order to iterate through all the checked checkboxes, you can simply run this selector: document.querySelector('.checkbox:checked'). To iterate through this Node collection, you can use Array.prototype.forEach().
Another note: you might want to return from the function if there an empty text is provided when a user wants to add a textbox.
See proof-of-concept example below:
function add() {
var myDiv = document.getElementById("myDiv");
var inputValue = document.getElementById("myInput").value;
// creating checkbox element
var checkbox = document.createElement('input');
if (inputValue === '') {
alert("Input is Empty!");
return;
} else {
document.getElementById("myUL").appendChild(checkbox);
}
// Assigning the attributes to created checkbox
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.classList.add("checkbox");
// create label for checkbox
var label = document.createElement('label');
// appending the checkbox and created text to the created label tag
label.appendChild(checkbox);
label.appendChild(document.createTextNode(inputValue));
// appending label to div
myDiv.appendChild(label);
}
function remove() {
const checkboxes = document.querySelectorAll('.checkbox:checked');
Array.prototype.forEach.call(checkboxes, function(checkbox) {
checkbox.closest('label').remove();
});
}
<h1>To Do List</h1>
<input type="text" id="myInput">
<button onclick='add()'>Click me!</button>
<button onclick="remove()">Delete</button>
<ul id="myUL">
<div id="myDiv"></div>
</ul>
I think you should restructure your html. Create a separate function createItem() which
returns a <div> containing <input> and text. Give a specific className to container div.
Inside remove() you querySelectorAll() to get all items. And use forEach() to loop through items and check if the input of item is checked then remove() it
Note: id of the element in whole document should be unique
function createItem(text){
const container = document.createElement('div');
container.className = 'item'
container.innerHTML = `<input type="checkbox" /><span>${text}</span>`
return container;
}
function add() {
var myDiv = document.getElementById("myDiv");
var inputValue = document.getElementById("myInput").value;
// creating checkbox element
var checkbox = document.createElement('input');
if (inputValue === '') {
alert("Input is Empty!");
} else {
document.getElementById("myUL").appendChild(createItem(inputValue));
}
}
function remove() {
var doc = document.querySelectorAll('.item');
doc.forEach(x => {
if(x.querySelector('input').checked){
x.remove()
}
})
}
<h1>To Do List</h1>
<input type="text" id="myInput">
<button onclick='add()'>Click me!</button>
<button onclick="remove()">Delete</button>
<ul id="myUL">
<div id="myDiv"></div>
</ul>
Use a query:
function removeCheckedCheckboxes() {
const query = document.querySelectorAll('[type="checkbox"]:checked');
Array.from(query).forEach(element =>
element.remove()
);
}
<html>
<body>
<span style="background: red; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: orange; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: yellow; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: green; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: blue; display: inline-block">
<input type="checkbox">
</span>
<br>
<span style="background: purple; display: inline-block">
<input type="checkbox">
</span>
<br>
<br>
<button onclick="removeCheckedCheckboxes()">
Remove checked checkboxes
</button>
</body>
</html>

How to get the value of user text input of user created input, jQuery

I have created a button that lets the user create a new text input. I am trying to get the value of the text input of the newly created input.
HTML
<div class='pop-up-box-radio' Title="Edit Radios">
<div style="display: inline; float: left; margin-left: 5%;">
<div style="clear: both;">
<ul class="new-radios"></ul>
</div>
<p style="padding-top: 15px;">
<input type="button" class="add-radio" value="New Radio" />
</p>
<p>
<input type="button" class="values" value="Values" />
</p>
<p class="theValues"></p>
</div>
</div>
jQuery
// ADD RADIO
$('.add-radio').click(function(){
$("ul.new-radios").append("<li class='radioLi'><div style='dispaly: inline;'><input class='added-radio' type='text' style='width: 150px;' /><input type='button' class='deleteRadio' value='X' /></div></li>");
});
// GET VALUE OF INPUT
var newRadio = $('input.added-radio').val();
$('.values').click(function(){
$("p.theValues").append("<p>" + newRadio + "</p>");
});
// DELETE RADIO
$('div.pop-up-box-radio').on('click', 'input.deleteRadio', function() {
var clickedButton = $(this);
clickedButton.parent().remove();
});
When the value button is clicked, the only response I get is 'undefined'.
JSfiddle
You need a slight amendment to your JS to be able to find the new element you have found.
Firstly, var newRadio will run on browser load and not on the click function to create a new input. Your best option is to run it when clicking the .values button.
Secondly, .click() cannot find dynamically created elements. If you change this out be a .on('click' function, it will be able to find the dynamically added element.
Third and lastly, this will only find one element and not find all of them. If you make an each() function and loop through, you will be able to find all of the inputs.
// ADD RADIO
$('.add-radio').click(function() {
$("ul.new-radios").append("<li class='radioLi'><div style='dispaly: inline;'><input class='added-radio' type='text' style='width: 150px;' /><input type='button' class='deleteRadio' value='X' /></div></li>");
});
$('.values').on('click', function() {
var list = ''; // create list variable
$('input.added-radio').each(function() { // start each loop
var curRadio = $(this).val(); // get value of current item
list += curRadio + ' - '; // append it to the list
}); // end loop
$("p.theValues").append("<p>" + list + "</p>"); // append list to the page
});
// DELETE RADIO
$('div.pop-up-box-radio').on('click', 'input.deleteRadio', function() {
var clickedButton = $(this);
clickedButton.parent().remove();
});
li {
list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pop-up-box-radio' Title="Edit Radios">
<div style="display: inline; float: left; margin-left: 5%;">
<div style="clear: both;">
<ul class="new-radios"></ul>
</div>
<p style="padding-top: 15px;">
<input type="button" class="add-radio" value="New Radio" />
</p>
<p>
<input type="button" class="values" value="Values" />
</p>
<p class="theValues"></p>
</div>
</div>
Your newRadio var is grabbing the value of $('input.added-radio') on initial page load (undefined, as no new fields have been added yet).
Your JSFiddle works if you move the .val() update inside your click function
$('.values').click(function(){
// GET VALUE OF INPUT
var newRadio = $('input.added-radio').val();
$("p.theValues").append("<p>" + newRadio + "</p>");
});
Updated JSFiddle
As an aside, $('input.added-radio').val() will only grab the value from the first field if multiples exist
Get the current value of the first element in the set of matched elements...
(from the .val() api)
So if a user clicks New Radio twice and enters text in both fields, only the value from the first one will be appended when your Values button is clicked.
If the first field is closed by clicking the X to the right, then the value from the next field will be used.
Your current implementation is only going to give you the value from the first dynamically created input control. Therefore, you would need to iterate through each element.
$('.values').click(function(){
$('input.added-radio').each(function(i,op)
{
$("p.theValues").append("<p>" + $(this).val() + "</p>");
});
});
Fiddle : http://jsfiddle.net/91e4a7wy/30/

Categories