I have a form where there is a an input. The user can click an add button and another input will appear under it and so on.
The problem I am having is how do I add an input to the DOM on a click event.
My first thought was using an ngFor or v-for (I'm using both, answer can be in either). When I click the add button, it increments a counter and the counter is then pushed into an array. Then using the for it will display the inputs.
let inputs = 0;
addInput() {
this.inputs++;
this.criteria.push(this.inputs);
}
<button #click.prevent='addInput'>Add input</button>
<input type='text' value='Default Input'>
<div v-for="input in inputs" v-bind:key="input">
<input type='text'>
</div>
It works as originally thought. A new input appears when the button is clicked.
The problem occurs when I add a second input, enter a value, then add a third input. The second input's value is reset to blank.
How can I implement this feature, adding inputs on click, but saving the values on the previous inputs?
Thanks.
If you bind the value of the input (using v-model) to a value in your inputs array, it should keep your values - even when adding a new input.
let inputs = [];
addInput() {
this.inputs.push({value: ""});
}
<button #click.prevent='addInput'>Add input</button>
<input type='text' value='Default Input'>
<div v-for="(input, index) in inputs" v-bind:key="index">
<input v-model="input.value" type='text'>
</div>
Related
I would like to add another input field into the form each time I click the button in the code below. Using appendChild(), it seems as though I can only do this one time. I tried adding the field using innerHTML, but this removes what has already been typed in the existing form fields. What would be the best way to achieve this with vanilla JavaScript while keeping what has already been typed into the form? Thank you in advance for your help.
let getArticleForm = document.getElementById("articleForm");
let cloneInputNode = document.getElementById("textInput").cloneNode(true);
cloneInputNode.setAttribute("id", "newId");
function addInput() {
getArticleForm.appendChild(cloneInputNode);
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
Codepen
Clone it inside the listener, else you've only created one clone (which gets removed from its prior location when appended again).
let getArticleForm = document.getElementById("articleForm");
function addInput() {
getArticleForm.appendChild(document.getElementById("textInput").cloneNode(true));
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
But there are some other fixes to make too:
The cloned nodes will all have the same ID, which is invalid HTML. While you could set a new ID for each input, dynamic IDs are an antipattern anyway - better to leave it off entirely IMO.
type="textarea" doesn't make sense as an attribute on an <input>. If you want a textarea, use a <textarea>.
Instead of cloning the existing input, consider just appending a new input.
const getArticleForm = document.getElementById("articleForm");
function addInput() {
getArticleForm.appendChild(document.createElement('input'));
}
<form id ='articleForm'>
<input id="textInput" type="textarea"></input>
</form>
<button onClick="addInput()">add input</button>
I have three inputs in the following form. Two inputs type is text and another one input type is hidden. Now when I click the submit button then two input values need to set the hidden input before run the ajax query. Because, ajax will get the data from the hidden input only. I have tried it myself but, it's not working for me. Now, when I click the submit ajax working first then set the both values to hidden input.
<form>
<input type="text" class="date" value="2018-11-09">
<input type="text" class="time" value="15:00:00">
<input type="hidden" class="date-time" value="">
<button type="button" class="button">Submit</button>
</form>
For the following code I am assuming that the 'Submit' button has its type changed to 'submit' as this will give you more control of when the form is submitted:
$('form').submit(function(event) {
event.preventDefault(); // stop the form from automatically submitting
$('.date-time').val($('.date').val() + $('.time').val());
console.log($('input[type=hidden').val());
// call your ajax here
});
The important line here for your question is:
$('.date-time').val($('.date').val() + $('.time').val());
This sets the value of the input .date-time to the input of .date and .time, although I would recommend using ids instead of classes as they are unique
I have yet another question concerning this project but here's hoping ill learn a lot from it.
So I created a function, that creates a div inside a div (which will then contain a random number from dice roll) and it works when I add this function to a button click.
But clicking the button multiple times might not be ideal for a lot of dice, so I created a form and it shouldnt create the number of divs the user decides he wants, but it doesnt seem to work. I suspect it has to do with the form refreshing the page, so instead of handling the even withh addEventListener I used inline "onsumbit" and tried to return the function but it still doesnt seem to work. What am i doing wrong? Here is the HTML and JS bits:
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onsubmit="return addMoreDice()">
</form>
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
and JS:
var numInput = document.querySelector("input");
function addDice(){
var div = document.createElement('div');
div.className = "diceStyle";
div.innerHTML = "<p> here will be a dice</p>";
document.getElementById('diceTable').appendChild(div);
};
function addMoreDice(){
for(var i = 0; i < numInput; i++){
addDice();
}
}
1.You should probably include onsubmit() in form tag and add a submit button inside form.
You can use onchange() method to invoke addMoreDice() whenever the value in input box is changed
you need to add onsubmit="yourfunction()" in side form tag
and than put an input type submit inside form tag like
<form action="#" onsubmit="addDice()">
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onsubmit="return addMoreDice()">
<input type="submit" value="Submit">
</form>
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
Each time you submit a form, it gets you to a different page. Instead you could have this code as shown below, (remove form tags)
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber"></input>
<input type="submit" onClick="addMoreDice()">
Clicking on submit after entering the input dynamically creates divisions per your need.
Is it somehow possible to restore only a part of a form? For example I want to reset everyhting in fieldset #1 but keep all other values in fieldset #2:
<form>
<fieldset id="1">…</fieldset>
<fieldset id="2">…</fieldset>
</form>
I could of course use a JavaScript-/jQuery-solution like this (written by heart, not tested):
$('#1 :input').val('');
But this wouldn't restore previously set default values. Or I must store all default values beforehand and I have to check for textareas, inputs, checkboxes etc … Is there another way of doing this?
Not sure if this is what you meant, but this will filter all fieldsets which do not have an id of two and then reset the form elements within those fieldsets to their default values (please note that defaultValue will only work for input/textareas!):
$(document).ready(function() {
$('#btn-reset').on('click', function(e) {
e.preventDefault();
$('form > fieldset').filter(function() {
return $(this).prop('id') !== 'two';
}).children(':input').each(function() {
$(this).val(this.defaultValue);
});
});
});
example markup
<form>
<fieldset id="one">
<input type="text" value="this is a default value" />
<textarea>this is another default value</textarea>
<p>this paragraph doesn't get looped over</p>
</fieldset>
<fieldset id="two">
<input type="text" value="text here.." />
<textarea>hello world!</textarea>
</fieldset>
<button id="btn-reset">Reset</button>
</form>
Here's a fiddle
Change all of the values, then click reset, all of the values in the first fieldset will be reset to their default values, whilst the second set will remain untouched.
There is no way of doing this without JavaScript... The reset button will always reset the whole form element.
Hope this will solve your problem
http://www.electrictoolbox.com/jquery-clear-form/
You can do this using KnockoutJS. Create a view model with default values.
I have the below piece of code
<input type="text" />
<button> Submit </button>
Now, when the user types some input and clicks on the submit button, I want the input text to become non-editable but the text should still be there.Also, the submit button should dissapear. Moreover, below the input text box, i want to creat another input text with the similar to the original one with a submit button. So, this is somethings like a commenting system. Any idea on how to do this using javascript.
A very simple way to do this is below. For unobtrusive Javascript, however, you should bind the onclick event to the button programmatically. Or better yet, use jQuery, which always abstracts events, which is why we love it so.
<script>
function disableInput() {
document.getElementById("foo").disabled = true;
document.getElementById("bar").style.display = "none";
}
</script>
<input id="foo" type="text" value="Some Text" />
<button id="bar" onclick="disableInput();"> Submit </button>
Try this solution at jsFiddle
If you will be duplicating content be sure to remove id's. They must be unique per page. Here is the html:
<p class="comment">
<input type="text" value="Initial Text" />
<button>Submit</button>
</p>
Using jQuery we bind to all future buttons using live. When the button is clicked, clone the row, disable the field, and remove the button. Finally re-insert the cloned paragraph after this one:
// Execute when document is ready
$(function() {
// Bind click handler to all current and future button elements
$('.comment button').live('click', function() {
// Find the paragraph this button is in and clone it
var p = $(this).closest('p'),
row = p.clone();
// Disable text field
$(this).prev().attr('disabled',true);
// Hide submit button for this row
$(this).hide();
// Insert a new field/button pair below this one
p.after(row);
});
});
<input type="text" />
<button> Submit </button>
$('button').click(function() {
$(this).hide();
$('input').prop('disabled', true);
})
Example