I created a small website where I would like to add/remove input fields dynamically. I already wrote the code to add them and it works perfect but removing the input fields is a bit of a challenge.
Below is what my document looks like after creating the inputs. Now with the "remove button" I tried to remove the last BR and the 3 inputs fields above, but whatever I try I always remove the last 3 buttons, which is ok, and both brs above and beneath the three inputs.
var total_inputs = 9;
var place_br_before = false;
function remove_inputs() {
if (total_inputs != 0) {
place_br_before = true;
for (var j = 0; j < 3; j++) {
var del = document.getElementById(("input_" + total_inputs));
del.remove();
total_inputs--;
}
$('#inputs br:last-child').remove();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button type="button" onclick="add_inputs()">+</button>
<button type="button" onclick="remove_inputs()">-</button>
<form id="inputs">
<input type="text" id="input_1">
<input type="text" id="input_2">
<input type="text" id="input_3">
<br>
<input type="text" id="input_4">
<input type="text" id="input_5">
<input type="text" id="input_6">
<br>
<input type="text" id="input_7">
<input type="text" id="input_8">
<input type="text" id="input_9">
<br>
</form>
I would probably simplify and abstract out the ID requirement by grouping rather than using line breaks.
function remove_inputs() {
inputGroups = document.getElementsByClassName('input-group');
inputGroups[inputGroups.length - 1].remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button type="button" onclick="add_inputs()" disabled>+</button>
<button type="button" onclick="remove_inputs()">-</button>
<form id="inputs">
<div class="input-group">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="input-group">
<input type="text">
<input type="text">
<input type="text">
</div>
<div class="input-group">
<input type="text">
<input type="text">
<input type="text">
</div>
</form>
Related
I need to write a javascript function that will loop through the input boxes and concatenates the text in each field together and displays the result in the result box. I tried multiple solutions and haven't been able to get any to work, I get that it needs an array of text fields but I can't seem to work it out.
<!DOCTYPE html>
<html>
<body>
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" onClick="myFunction()" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
<script>
function myFunction() {
var fields = [];
}
</script>
</body>
</html>
You can use filter and map
NOTE: I gave the button an ID of "btn"
document.getElementById('btn').addEventListener('click', function() {
const conc = [...document.querySelectorAll('#myform [id^=text]')] // id starts with text
.filter(fld => fld.value.trim() !== "") // not empty
.map(fld => fld.value) // store value
document.getElementById('result').value = conc.join(","); // join with comma
})
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" id="btn" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
In one pass:
document.getElementById('btn').addEventListener('click', function() {
const res = [];
[...document.querySelectorAll('#myform [id^=text]')]
.forEach(fld => { const val = fld.value.trim(); if (val !== "") res.push(val) })
document.getElementById('result').value = res.join(","); // join with comma
})
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" id="btn" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
function myFunction() {
const data = document.querySelectorAll("#myform input[type='text'][id^=text]");
//console.log(data);
var fields = [];
data.forEach(item => {
if (item.value != '') {
fields.push(item.value)
}
})
document.getElementById("result").value = fields.join(",")
}
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" onClick="myFunction()" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
I have this function:
calculatetabel1 = function(){
a1 = document.getElementById('pnpa1').value;
a2 = document.getElementById('pnpa2').value;
a3 = document.getElementById('pnpa3').value;
a4 = document.getElementById('pnpa4').value;
a5 = document.getElementById('pnpa5').value;
document.getElementById('totalpnp1').value =parseInt(a1)+parseInt(a2)+parseInt(a3)+parseInt(a4)+parseInt(a5);
}
This function works perfectly using onkeyup="calculatetabel1()".
Let's say I have 20 columns and rows. How do I call this function without filling 20 columns and rows? (only 1 column will do)
I already tried document.addEventListener("DOMContentLoaded", function(event) { calculatetabel1(); This does not work as I expected.
If you want to trigger this function whenever any of the fields have changed, without needing to attach an onkeyup to each one, you could do something like this:
const form = document.getElementById("pnpForm");
form.addEventListener("input", function() {
let values = [];
const inputs = form.getElementsByTagName("input");
[...inputs].forEach(input => {
if (input.value && input.value !== '' && !input.readOnly) {
values.push(input.value);
}
});
form.querySelectorAll('[readonly]')[0].value = values.reduce((a, b) => parseInt(a) + parseInt(b), 0);
});
<form id="pnpForm">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text" readonly>
</form>
This can be further generalized to support multiple tables without any extra logic:
const forms = document.getElementsByTagName("form");
[...forms].forEach(form => {
form.addEventListener("input", function() {
let values = [];
const inputs = form.getElementsByTagName("input");
[...inputs].forEach(input => {
if (input.value && input.value !== '' && !input.readOnly) {
values.push(input.value);
}
});
form.querySelectorAll('[readonly]')[0].value = values.reduce((a, b) => parseInt(a) + parseInt(b), 0);
});
});
<h3>Table 1</h3>
<form id="table1">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text" readonly>
</form>
<h3>Table 2</h3>
<form id="table2">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text" readonly>
</form>
Maybe this code seemingly works the same as the one you delivered above:
calculatetabel1 = function() {
// got an array of document.getElementById('pnpa ... ').value
const arr = Array.from({ length: 5 }).map( (_, i) => {
const idToGet = `pnpa${i+1}`;
return document.getElementById(idToGet).value;
});
// calculate total
const total = arr.reduce( (a, b) => {
return parseInt(a) + parseInt(b);
}, 0);
// assign to #totalpnp1
document.getElementById('totalpnp1').value = total;
}
I have three fields that will be filled by the user.
one for the question, and the two others for the proposed answers. I want to give the user the possibility to add the third or as much as he wants propositions whenever he clicks at add proposition. I started coding the function but it's still missed
<head>
<script>
function myFunction(){
var x = document.createElement("LABEL");
var t = document.createTextNode("Titre");
x.appendChild(t);
}
</script>
</head>
<body>
<form id="myForm" method="POST" action="./exam_coordinates">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="checkbox" name="ans1" id="ans1" values="" />
<input type="text" name="ans1" id="ans1" value=""><br>
<input type="checkbox" name="ans2" id="ans2" />
<input type="text" name="ans2" id="ans2" value=""><br>
<br>
<button onclick="myFunction()">Add proposition</button> <br><br><br>
<input type="submit" value="submit">
</form>
</body>
If I'm getting your question right, you need to add inputs to get more answers from user as he wants. If so, see the following -
var addButton = $('#add_button');
var wrapper = $('#more_answers');
$(addButton).click(function(e) {
e.preventDefault();
var lastID = $("#myForm input[type=text]:last").attr("id");
var nextId = parseInt(lastID.replace( /^\D+/g, '')) + 1;
$(wrapper).append(`<div><input type="checkbox" name="ans${nextId}" id="ans${nextId}" values="" /> <input type="text" name="ans${nextId}" id="ans${nextId}" value=""/>Delete<div>`);
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form id="myForm" method="POST" action="./exam_coordinates">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="checkbox" name="ans1" id="ans1" values="" />
<input type="text" name="ans1" id="ans1" value=""><br>
<input type="checkbox" name="ans2" id="ans2" />
<input type="text" name="ans2" id="ans2" value=""><br>
<div id="more_answers"></div>
<br>
<button id="add_button">Add proposition</button> <br><br><br>
<input type="submit" value="submit">
</form>
</body>
In your function, you have to append your label as well in its parent. Like below -
function myFunction() {
var form = document.getElementById("myForm");
var input = document.createElement("input");
form.appendChild(input)
}
<form id="myForm" method="POST" action="./exam_coordinates">
<label for="question"> Question </label> <br>
<input class="champ" type="textarea" name="question" id="question" value=""><br><br>
<label for="ans"> Answers </label> <br>
<input type="checkbox" name="ans1" id="ans1" values="" />
<input type="text" name="ans1" id="ans1" value=""><br>
<input type="checkbox" name="ans2" id="ans2" />
<input type="text" name="ans2" id="ans2" value=""><br>
<br>
<button type="button" onclick="myFunction()">Add proposition</button> <br><br>
<input type="submit" value="submit">
</form>
If you want to put your elements at any specific place, you should create a wrapper in your form element just like below -
function myFunction() {
let wrapper = document.getElementById("dynamic-fields");
var input = document.createElement("input");
wrapper.appendChild(input)
}
<form>
<!-- ...input fields... -->
<div id="dynamic-fields"></div> <br>
<!-- ...buttons.... -->
<button type="button" onclick="myFunction()">Add proposition</button>
</form>
This way it will put those dynamically generated elements on specific place in your form page.
Try this - https://jsitor.com/IO08f-WBx
I have 3 textboxs and 6 buttons. I want to add new textbox and buttons after textbox(element2) and buttons(element2) with javascript. How can I do it. :)
<input type="text" id="element1">
<input type="button" id="element1">
<input type="button" id="element1">
<input type="text" id="element2">
<input type="button" id="element2">
<input type="button" id="element2">
<input type="text" id="element3">
<input type="button" id="element3">
<input type="button" id="element3">
Since Ids should be unique, I'll modify your HTML code :
<div id="div">
<input type="text" id="text1">
<input type="button" id="button1a">
<input type="button" id="button1b">
<input type="text" id="text2">
<input type="button" id="button2a">
<input type="button" id="button2b">
<input type="text" id="text2">
<input type="button" id="button2a">
<input type="button" id="button2b">
</div>
And the script would look like this :
<script>
var text2_new = document.createElement("input");
var div= document.getElementById("div");
var button2b= document.getElementById("button2b");
div.insertBefore(text2_new,button2b);
</script>
Repeat the the script for every new element you need to add.
In your context I'd place the group of inputs inside of <div> tags to delimit the groups.
I have a form where the user enters an amount of money. They click a button which updates a span and the PayPal form.
Problem is that when I click update i get nothing. only £ .00 so there is no price.
html
<label>Reason for Payment</label>
<input type="text" id="reason" class="form-control" placeholder="Reason">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Total Amount</label>
<input type="text" id="value" class="form-control input-small" placeholder="Amount">
</div>
</div>
<div class="ptotal">
<span class="total">£ 20.00</span>
</div>
<div class="calculator-submodule">
<button class="btn theme-btn" id="update">Update Price</button>
<div class="calculator-total">
<form action="https://www.paypal.com/uk/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="currency_code" value="GBP">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="my#email.com">
<input type="hidden" name="item_name_1" id="trip" value="Canterbury & Brighton">
<input type="hidden" name="amount_1" id="value" value="150" >
<input type="hidden" name="shipping_1" value="0">
<input type="submit" class="btn green" value="Buy Now">
</form>
js
<script>
$('#update').click(function () {
var price = $("#amount").text();
total = $('.total'),
value = $('#value'),
reason = $('#reason')
total.text("£ " + price + ".00");
value.val(price);
trip.val(reason);
});
</script>
You're getting price from a non-existent element.
var price = $("#value").val();
That seems to be what you're looking for. Live demo (click).
It also seems that you're missing some code because trip is undefined.
Can you try this, Assumed you have $("#amount") in your form, I have found only half of your form.
var price = $("#amount").val(); //instead of var price = $("#amount").text();
var total = $('.total'),
value = $('#value'),
reason = $('#reason');
I couldn't find trip for trip.val(reason);