Add and remove inputs dynamicly with a other input - javascript

I searched a lot for this, but I can only find +1 -1 solutions.
But I want to set the number of inputs with a other input like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
When the user now writes 5 in the first field, the form should look like this:
//Enter the number of inputs (1 is the start-value)
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
//Display that number of inputs (1 at start)
<input type="text" size="30" maxlength="30" id="input_1" name="input_1">
<input type="text" size="30" maxlength="30" id="input_2" name="input_2">
<input type="text" size="30" maxlength="30" id="input_3" name="input_3">
<input type="text" size="30" maxlength="30" id="input_4" name="input_4">
<input type="text" size="30" maxlength="30" id="input_5" name="input_5">
How can I make this? MUST I use js?

Here's a simple javascript snippet that doesn't make use of any frameworks:
function addInputs() {
var count = parseInt(document.getElementById("count").value);
for (var i = 2; i <= count; i++) {
document.getElementById('moreinputs').innerHTML += '<input type="text" name="input_' + i + '" id="input_' + i + '" />';
}
}
In this example you have to add a container (div) with id 'moreinputs'. However, when calling this function more than once, it will not work properly (e.g. it can only increase the number of input but not decrease)

Yes, either you use javascript, or you send the form to the server, where a new html page with all the inputs is generated (e.g. with PHP).

Yes you must use js to do it dynamically on the spot You have a jQuery tag so I will show an example in jQuery
This is not the best example but it works and it's a starting point
JS:
$(function(){
$('#master').on('change', function() {
var count = $(this).val();
$('#otherInputs').html('')
for( var i = 0; i < count; i++) {
$('#otherInputs').append(
$('<input>', {type: 'text'})
);
}
});
});
HTML:
<input type="number" id="master" value="1">
<div id="otherInputs"></div>
Demo
In English this is saying...
When you change #master I will empty #master (html('')) loop through and append a new input depending on #master's value

Here's the FIDDLE. Hope it helps. :)
html
<input type="text" size="3" maxlength="3" id="count" name="count" value="1">
<div id="container"></div>
script
$('#count').on('keyup', function () {
var $this = $(this);
var count = $this.val();
$('#container').empty();
for (var x = 1; x <= count; x++) {
var newInput = '<input type="text" size="30" maxlength="30" id="input_' + x + '" name="input_' + x + '">';
$('#container').append(newInput);
}
});

This worked for me
function AddField() {
var count = $("#countetfield").val();
var i = 1;
var id = $("#container .testClass:last").attr('name');
var test = id.split("_");
id_name = test[1];
while (i <= count) {
id_name++;
var a = '<input type="text" class="testClass" size="30" maxlength="30" id="input_' + id_name + '" name="input_' + id_name + '"/>';
$("#container").append(a);
i++;
}
}
<input type="text" id="countetfield" value="1" />
<input type="button" value="Go" onclick="AddField();" />
<div id="container">
<input type="text" class="testClass" size="30" maxlength="30" id="input_1" name="input_1" />
</div>

Related

How to pass individual info to specific input field from select option list view using jquery

firebase.auth().onAuthStateChanged(function(user) {
console.log(user);
if (user) {
var user_id = user.uid;
firebase.database().ref('Clients/'+user_id)
.once('value').then(function(snapshot){
snapshot.forEach(function(childSnapshot) {
var client_name = childSnapshot.child("client_name").val();
var client_phone = childSnapshot.child("client_phone").val();
var client_address = childSnapshot.child("client_address").val();
var total = client_name + "<br>" + client_phone + "<br>" + client_address;
console.log(total);
$('.client_option').append('<option>' + total +'</option');
});
})
}
else{
window.location.href="{% url 'login' %}";
}
});
In this code, I already got individual client information. I have 3 input fields. As these values are displayed as options, I want that, when the user selects a set of options(client_name, phone, address), the individual info passes to specific fields. Here are my input fields.
<input type="text" class="form-control" id="clientName" list="client"
autocomplete="off">
<datalist class="form-control client_option" id="client" hidden>
</datalist>
<input type="tel" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" id="phone"
class="form-control" autocomplete="off">
<input type="text" class="form-control" id="address" autocomplete="off">
Thanks in advance.
function disp(){
var client_name = $('#client_name').val();
var client_phone = $('#client_phone').val();
var client_address = $('#client_address').val();
var total = client_name + "-" + client_phone + "-" + client_address;
$('.client_option').append('<option>' + total +'</option');
}
$(document).on("change", ".client_option", function(){
var valArr = $(".client_option option:selected").text().split("-");
$("#clientName").val(valArr[0]);
$("#phone").val(valArr[1]);
$("#address").val(valArr[2]);
$("#client").append("<option>" + $(".client_option option:selected").text() + "</option>");
});
<input id="client_name"> </input>
<input id="client_phone"> </input>
<input id="client_address"> </input>
<button type="submit" onclick="disp()">Submit</button>
<select class="client_option"><option>Please Select</option></select>
<input type="text" class="form-control" id="clientName" list="client"
autocomplete="off">
<datalist class="form-control client_option" id="client" hidden>
</datalist>
<input type="tel" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}" id="phone"
class="form-control" autocomplete="off">
<input type="text" class="form-control" id="address" autocomplete="off">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try this out to make this example I have replaced the childSnapshopt.child but it should work as same.
The big point is you can use text() to insert the text into an element.
I also suggest that you use template strings to build your string. Then there is no need of the string concat.
function disp(){
var client_name = $('#client_name').val();
var client_phone = $('#client_phone').val();
var client_address = $('#client_address').val();
var total = `${client_name} \n${client_phone} \n${client_address}`
console.log(total);
$('.client_option').text('<option>' + total +'</option');
}
<input id="client_name"> </input>
<input id="client_phone"> </input>
<input id="client_address"> </input>
<button type="submit" onclick="disp()"></button>
<div class=".client_option"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

How can i update the text of more than one label with the same class name using the input blur event

I am working in a project and i have to update the text of a label when the focus is losed in the input
This is the html part:
<input id="FirstName" name="FirstName" type="text" value="" class="inputName"/>
<input id="MidName" name="FirstName" type="text" value="" class="inputName"/>
<input id="LastName" name="FirstName" type="text" value="" class="inputName"/>
<p class="passengerTitle1">hola</p>
<input id="FirstName" name="FirstName" type="text" value="" class="inputName"/>
<input id="MidName" name="FirstName" type="text" value="" class="inputName"/>
<input id="LastName" name="FirstName" type="text" value="" class="inputName"/>
<p class="passengerTitle1">hola</p>
and the js code of firing the blur event of the inputs is:
$(document).ready(function () {
fullName = '';
$(".inputName").blur(
function (event) {
var name = $(this).val();
fullName += name+ ' ';
$(".passengerTitle1").text(fullName);
}
);
});
I get the following result:
the text of both labels: Phellip E. Summer Edgar B. Thompson
But the expected result is :
for the first label Phellip E. Summer
for the second label Edgar B. Thompson
this is the jsfiddle link:jsfiddle lin
I wonder for a little help because it a very important project and don't want to miss the deadline of the project.
cheers.
As others have proposed solutions by changing the html, I'm proposing a solution to implement this without changing the html (if you want to stick to your current html).
Use .nextAll() and .first() like this:
$(this).nextAll(".passengerTitle1").first().text(fullName);
Implemented on your fiddle: JSFiddle
But you also have another problem, where you are not properly setting the fullName variable.
Again, if you don't want to change the html, you could solve it using .prev() like this:
JSFiddle
You may need to make some changes in your html.
I hope this is what you want to achieve.
$(".inputName").on("blur", function() {
var inputName = $(this).parent(".passengerInfo").children(".inputName");
var outputName = "";
$(inputName).each(function() {
outputName += $(this).val() + " ";
})
$(this).parent(".passengerInfo").children(".passengerTitle1").text(outputName)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="passengerInfo">
<input id="FirstName" name="FirstName" type="text" value="" class="inputName" />
<input id="MidName" name="FirstName" type="text" value="" class="inputName" />
<input id="LastName" name="FirstName" type="text" value="" class="inputName" />
<p class="passengerTitle1">hola</p>
</div>
<div class="passengerInfo">
<input id="FirstName" name="FirstName" type="text" value="" class="inputName" />
<input id="MidName" name="FirstName" type="text" value="" class="inputName" />
<input id="LastName" name="FirstName" type="text" value="" class="inputName" />
<p class="passengerTitle1">hola</p>
</div>
$(document).ready(function () {
$(".inputName").blur(
function (event) {
var titel = getPassengerTitel($(this)); // find the titel element
var fullName = getName(titel); // read Fullname by titel element
titel.html(fullName);
}
);
});
function getName(passengerTitelElem){
var last = passengerTitelElem.prev();
var middel = last.prev();
var first = middel.prev();
var name ='';
if(first.val()) name += first.val() + ' ';
if(middel.val()) name += middel.val() + ' ';
if(last.val()) name += last.val() + ' ';
return name;
}
function getPassengerTitel(e) {
var next = e.next();
if(next.attr('class') == 'passengerTitle1') {
return next;
}
return getPassengerTitel(next);
}

jquery sum of multiple input fields if same class in one input

Hello I need to sum the values of same class input in one input with class name total.
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
Possible?
A working fiddle here
$(document).on("change", "qty1", function() {
var sum = 0;
$("input[class *= 'qty1']").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
You pretty much had it, just needed to adjust your JQuery a little bit for the appropriate selectors
updated fiddle : http://jsfiddle.net/5gsBV/7/
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
I suggest this solution:
html
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
<div id="result"></div>
js
$(".qty1").on("blur", function(){
var sum=0;
$(".qty1").each(function(){
if($(this).val() !== "")
sum += parseInt($(this).val(), 10);
});
$("#result").html(sum);
});
fiddle
I think your issue is here:
$("#destination").val(sum);
change it to:
$(".total").val(sum);
And instead of change event i suggest you to use keyup instead.
$(document).on("keyup"
$(document).on("keyup", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
We can use following own function
(function( $ ){
$.fn.sum=function () {
var sum=0;
$(this).each(function(index, element){
sum += parseFloat($(element).val());
});
return sum;
};
})( jQuery );
//Call $('.abcd').sum();
http://www.gleegrid.com/code-snippet/javascript/jquery-sum-input-values-by-class/?filter=bygroup&group=JQuery
$('.qty1').each(function(){
sum += parseFloat(this.value);
});
console.log(sum);
This will work with pure js
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<p>Total Value :<span id="total">100%</span></p>
<p>Left Value :<span id="left">0.00%</span></p>
var percenInput = document.querySelectorAll('.percent-input');
for (let i = 0; i < percenInput.length; i++) {
percenInput[i].addEventListener('keyup', getPercentVal)
}
function getPercentVal() {
var total = 0;
var allPercentVal = document.querySelectorAll('.percent-input');
for (var i = 0; i < allPercentVal.length; i++) {
if (allPercentVal[i].value > 0) {
var ele = allPercentVal[i];
total += parseFloat(ele.value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2) + '%';
document.getElementById("left").innerHTML = (100 - total).toFixed(2) + '%';
}
You almost had it:
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
http://jsfiddle.net/DUKL6/1
The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.
$('body').on('change', '.qty1', function() {
var total=0;
$(".qty1").each(function(){
quantity = parseInt($(this).val());
if (!isNaN(quantity)) {
total += quantity;
}
});
$('.total').val('Total: '+total);
});
<input type="text" class="price" placeholder="enter number one" />
<input type="text" class="price" placeholder="enter number two" />
<input type="text" class="price" placeholder="enter number three" />
<input type="text" class="price" placeholder="enter number four" />
<input type="text" id="total">
<script>
$(document).ready( function() {
$(document).on("keyup", ".price", function() {
var sum = 0;
$(".price").each(function(){
sum += +$(this).val();
});
$('#total').val(sum);
});
});
</script>

Replace text in form using javascript

I have a form that has several fields. The first field is called subject. What I want to do is disable the ability for the user to type in the field, but it still show, and the text they enter into three other fields show up with spaces between the variables in the first field. Example: In this scenario: "Second_Field: John" "Third_Field: Doe" "Forth_Field: New part" then on first field, subject, it will show: John Doe New Part
Thanks for any help.
You can try the following:
<!-- HTML -->
<input type="text" id="subject" disabled="disabled">
<input type="text" id="field1">
<input type="text" id="field2">
<input type="text" id="field3">
// JavaScript
var fields = [];
for (var i = 1; i <= 3; i++) {
fields.push(document.getElementById("field" + i).value);
}
document.getElementById("subject").value = fields.join(" ");
Try this:
<script>
function UpdateText()
{
document.getElementById("subject").value =document.getElementById("Field1").value + " " + document.getElementById("Field2").value + " " + document.getElementById("Field3").value;
}
</script>
<input type="text" id="subject" disabled="disabled"/>
<input type="text" id="Field1" onchange="UpdateText()";/>
<input type="text" id="Field2" onchange="UpdateText()";/>
<input type="text" id="Field3" onchange="UpdateText()";/>
HTML:
<form>
<p><input id="subject" name="subject" disabled size="60"></p>
<p><input id="Second_Field" class="part">
<input id="Third_Field" class="part">
<input id="Fourth_Field" class="part"></p>
</form>
​
JavaScript:
var updateSubject = function() {
var outArray = [];
for (var i=0;i<parts.length;i++) {
if (parts[i].value !== '' ) {
outArray.push(parts[i].value);
}
}
document.getElementById('subject').value = outArray.join(' ');
};
var parts = document.getElementsByClassName('part');
for (var i=0;i<parts.length;i++) {
parts[i].onkeydown = updateSubject;
}
​

Categories

Resources