Create and Insert an Input on "Enter" - javascript

I am trying to create and insert an input(b) below another input(a) on "Enter" of input(a), while also inserting the value of input(a) into input(b).
Javascript
function add_name(ele) {
if(event.keyCode == 13) {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input id='person_holder' type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
var personName = document.getElementById("people").value;
document.getElementById('person_holder').value= personName;
}
}
HTML
<form>
<input type="text" class="add_name" onkeydown="add_name(this)" name="myInputs[]" id="people"/>
</form>

If this is your complete code, then I think the problem results from the default behavior of input text box in form. For a input text box in form, when it's focused and enter button is pressed, the form will be submitted, meaning the page will be reloaded. To prevent this, you can add event.preventDefault();. Here's the working demo.

Related

Showing form input on submit

I have a form with one input field and when I press enter I would like to see this input written under the form. I would like to have as many inputs as possible, each new one to be displayed under the previous one.
I tried it like this but I failed.
<form>
<input type="text" name="" value="" id="form-input">
</form>
<ul>
<li id="form-list"></li>
</ul>
And then inside my <script> tag:
var formInput = document.getElementById("form-input")
var formOutput = document.getElementById("form-list")
formOutput.innerHTML = formInput.value;
formInput.onsubmit = function() {
formOutput.innerHTML = this.value;
}
When I press enter it refreshes the page, if I change onsubmit to oninput it displays what I'm writing but it is not saved.
Is it possible to display multiple inputs like this? Thanks
I'm not sure if I understood your question correctly but here is one way to listen for the 'enter' key press on an input element and create a dynamic list of input elements with the entered value.
var inputEl = document.getElementById("in");
var targetList = document.getElementById("list");
function createItem(text){
var listItem = document.createElement('li');
var input = document.createElement('input');
input.type = 'text';
input.value = text;
listItem.appendChild(input);
targetList.appendChild(listItem);
}
inputEl.addEventListener('keydown', function(e) {
if (e.keyCode == 13) {
createItem(inputEl.value);
inputEl.value = '';
e.preventDefault();
return false;
}
})
<form>
<input id="in" type="text" name="" value="">
</form>
<ul id="list">
</ul>
When I press enter it refreshes the page, if I change onsubmit to
oninput it displays what I'm writing but it is not saved.
You can use cookies to store and persist data on every refresh
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
or WebStorage/Application Storage
https://www.w3schools.com/html/html5_webstorage.asp
But I really advise that learn to use server-side scripting with a database so your data will have permanent persistence across browser sessions
https://www.w3schools.com/php/default.asp
You can make your code run with these changes in HTML and your Javascript:
var formInput = document.getElementById("form-input")
var formOutput = document.getElementById("form-list")
function AddElement() {
var NewValue = formInput.value;
var li = document.createElement('li');
var text = document.createTextNode(NewValue);
li.appendChild(text);
formOutput.appendChild(li);
return false;
}
<form onsubmit="return AddElement();">
<input type="text" name="" value="" id="form-input">
</form>
<ul id="form-list"></ul>

Prevent a character from being entered in ALL text boxes on a page ASP.net

I have a panel that is used for programmatically creating textboxes. When a user clicks save, the values in these texboxes need to be concatenated and I need a character to separate each value. For this, I am using a comma (ASCII code 44). Because I am using a comma, I want to prevent any other commas from being entered in any of the textboxes in my textbox list. What would be the best way to go about doing this?
If jQuery is an option you can do
$(".no-comma-textbox").on("keydown", function(e){
if (e.which == 188){
e.preventDefault();
}
});
And all your textboxes should have class="no-comma-textbox".
(note: when I tested this 188 seems to be the correct value to use for comma at least in Chrome)
Try using oninput event attached to document , String.prototype.slice()
document.oninput = function(e) {
if (e.target.value.slice(-1) === ",") {
e.target.value = e.target.value.slice(0, -1)
}
}
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", "input2");
document.body.appendChild(input);
<input type="text" name="input0" />
<input type="text" name="input1" />

javascript: adding form on click

I would like to add new input form by clicking on a button.
The form that I have and I would like to add:
<input type="number" id="portdiv" name="ports" min="0" max="48" size="1"/>
The button to add the new form:
<input type="button" value="Add another" onClick="addInput('portdiv');"/>
The javascript function:
var counter = 1;
function addInput(divName){
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById(divName).appendChild(textbox);
counter++;
}
This code do not works and I have not any errors on javascript console.
I have have tried different solution for the javascript function:
var textbox = document.createElement('input');
textbox.type = 'text';
document.getElementById(divName).appendChild(textbox);
counter++;
AND
var newFields = document.getElementById(divName).cloneNode(true);
document.getElementById(divName).appendChild(newFields);
counter++;
Nobody of them works. How can be solved?
You are trying to append an input to a input! An input does not have child elements.
You need to append it to the parent element that holds the form elements. By the name of your variable it would be some sort of div element. You can either do it by the name of the div, or use parentNode.

Dynamically creating a specific number of input form elements

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

Edit placeholder html after entering username

To save space (and keep things more compact) I added a input box with a placeholder stating
<input id="username-search" placeholder="view another users work">
after adding the username, I'd like to change the text of the placeholder to something like
<input id="username-search" placeholder="viewing -theuser-'s work">
as well as remove the text added to the input box by the user, as when text is entered, the placeholder disappears.
Any ideas?
You can change the placeholder attribute dinamically as you need in an onchange event handler for the <input type="text"> :
<input id="username-search" placeholder="view another users work"
onchange="changePlaceholder(this)">
<script>
function changePlaceholder(input){
if (input.value == '') {
input.placeholder = "view another users work";
}
else {
input.placeholder="viewing " + input.value + "'s work";
input.value="";
}
}
</script>
JSFiddle.
Take into account that the <input>'s value will be cleared after onchange(), so you might want to keep an <input type='hidden'> with the last inputted value if there's something you wish to do with it outside onchange.
Pretty simple really. Try this:
var input = document.getElementById('username-search');
input.onclick = function() {
input.setAttribute('placeholder', "viewing " + input.value + "'s work");
input.value = '';
}
Type something in the box, and then click on the box. The value will be removed, but the placeholder will update with "viewing Adam's work".

Categories