if I have this:
function add(){
var val = document.getElementById("item").value;
document.getElementById("items").value = val;
}
<table>
<input type="text" name="item" id="item" value="" >
<input type="hidden" name="items[]" id="items[]" value="" >
<button onclick="add()" type="button"> Add</button>
</table>
so I just want add some values to input items[], It's possible? in javascript I use push(), but in this case I don't know what to do.
You should create a new items[] element for each value that you're adding. Then the middleware on the server should automatically create an array with all these values.
function add(){
var val = document.getElementById("item").value;
var item = document.createElement("input");
item.type = "hidden";
item.name = "items[]";
item.value = val;
document.getElementById("form").appendChild(item);
}
<form id="form">
<input type="text" name="item" id="item" value="">
<button onclick="add()" type="button"> Add</button>
</form>
Related
I am trying to create a hotel booking form with an increment counter which I have already setup. Its got 3 input fields and at the end there is a "group total" text input field. I need to ask if anyone could help me with the JS in order to counter the number of individuals in the total group box for when they incrementally add people in the 3 increment counters?
My code is as follows:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
textbox.value++;
}
function decrease() {
var textBox = document.getElementById("text");
textBox.value--;
}
function increase2() {
var a = 1;
var textbox2 = document.getElementById("text2");
textbox2.value++;
}
function decrease2() {
var textBox2 = document.getElementById("text2");
textBox2.value--;
}
function increase3() {
var a = 1;
var textbox3 = document.getElementById("text3");
textbox3.value++;
}
function decrease3() {
var textBox3 = document.getElementById("text3");
textBox3.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease()">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease2()">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase2()">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease3()">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase3()">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="">
</a>
You can simplify your code by adding this to all onclick function calls so we can know which element called the function and with that we can figure out it's parent along with the correct input element to increment. In the end we call the increaseTotal() or decreaseTotal() function to update the group total field.
Note: I'm guessing you don't want to be able to decrease a field beyond 0, so I added that constraint as an if statement in the decrease() function. I also made the totalPersons input field's value to default to 3 because all of the 3 other inputs default to 1.
Run and test:
function increase(el) {
var textbox = el.parentElement.querySelector('input');
textbox.value++;
increaseTotal();
}
function decrease(el) {
var textBox = el.parentElement.querySelector('input');
if(textBox.value > 0) { // <- if value is at least 1
textBox.value--;
decreaseTotal();
}
}
function increaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value++;
}
function decreaseTotal() {
var textBox = document.getElementById("totalPersons");
textBox.value--;
}
<h4>Please select the number of people who will be in each room</h4>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text" value="1" min="1" data-max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text2" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<div class="cart-plus-minus">
<button type="button" onclick="decrease(this)">-</button>
<input type="text" id="text3" value="1" min="1" max="2" readonly>
<button type="button" onclick="increase(this)">+</button>
</div>
<a href="" class="a-link">
<label> Group Total: </label>
<input id="totalPersons" type="text" placeholder="" value="3">
</a>
You could just increase/decrease the value attribute of the totalpersons element within the increase/decrease methods as well.
For example:
function increase() {
var a = 1;
var textbox = document.getElementById("text");
var totalpersons = document.getElementById("totalPersons");
textbox.value++;
totalpersons.value++;
}
Note that the values of text boxes are always strings in javascript. The parseInt() function will convert them to integers.
https://jsfiddle.net/y473L1bt/2/
function updateTotal() {
var textbox = document.getElementById("text");
var textbox2 = document.getElementById("text2");
var textbox3 = document.getElementById("text3");
var total = document.getElementById("totalPersons");
total.value = parseInt(textbox.value) +
parseInt(textbox2.value) + parseInt(textbox3.value);
}
function increase(id) {
var textbox = document.getElementById(id);
textbox.value++;
updateTotal();
}
function decrease(id) {
var textBox = document.getElementById(id);
var a = textBox.value - 1;
if (a >= 0) {
textBox.value = a;
}
updateTotal();
}
I have a textbox that can be append.. and i want to get the values of each textbox
$('#entryData').append('<div><input type="text" id="quantity"></div>');
var total = $('#quantity').val();
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="entryData">
<input type="text" id="quantity">
<input type="button" value="+">
<input type="button" value="Total">
</div>
but I am only getting the first textbox value and not the other textbox
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id='entryData' >
<input type="text" class='quantity'>
<input type="button" value="+" id='add'>
<input type="button" value="Total" id='total'>
</div>
<script>
$(document).ready(function(){
$('#add').click(function(){
$('#entryData').append('<div><input type="text" class="quantity"></div>');
});
$('#total').click(function(){
var total=0;
$('.quantity').each(function(index,quantity){
total=total+parseInt($(this).val());
});
alert(total);
});
});
</script>
I expect this is what you are trying to do?
Or make it like this:
<div id='entryData' >
<input type="number" class='quantity'>
<input type="button" value="+" id='add'>
<input type="button" value="Total" id='total'>
</div>
If you expect numbers - make the field number.
//this should come from helper method file/lib - for reusability
const sum = (accumulator, currentValue) => accumulator + currentValue;
const mapToInt = (idx,element) => { if (element.value !== "") { return parseInt(element.value, 10); } }
$(document).ready(() =>{
$('#add').click( () => {
$('#entryData').append('<div><input type="number" class="quantity" /></div>');
});
$('#total').click( () => {
let total = $(".quantity").map(mapToInt).get().reduce(sum);
console.log ( total );
});
});
Edit: sum (aggregation func) and mapToInt can be reused if you consider having more functional approach.
Normally if I add a new input tag I also have to add in Javascript.
I try to collect all value from input tag,
So how to pass value into an object by loop
use tag input name to be object key name also.
Try to use for count
document.getElementById("form1").elements.length
seem it collected the button tag also, how to void it
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" onClick="fc1()" value="Save">
</form>
for(i=0;......)
{
obj.value+'i' = document.forms["form1"]["value"+ (i+1)].value;
}
Same result as this.
function fc1(){
this.value1 = document.forms["form1"]["value1"].value;
this.value2 = document.forms["form1"]["value2"].value;
this.value3 = document.forms["form1"]["value3"].value;
this.value4 = document.forms["form1"]["value4"].value;
const obj = {
"value1": this.value1,
"value2": this.value2,
"value3": this.value3,
"value4": this.value4
};
}
I usually grab inputs by their ID or class:
<input type="text" id="value1">
then grab the value:
const value1 = document.getElementById('value1').value
to cut down on code, maybe throw it in an array:
const valueArray = [value1, value2, value3]
then you can do something like this:
const allValues = {}
valueArray.forEach((value, index) => {
allValues[`value${index + 1}`] = value
})
now when you log allValues you should have what you want. Note, I am using some es6.
What about this ?
var obj = {};
var form = document.getElementById("form1");
form.children.forEach(function(elm){
if(elm.type === 'text'){
obj[elm.name] = elm.value;
}
});
console.log(obj);
try giving same 'class' or 'name' attribute to the text fields.
try var x = document.getElementsByClassName("example");
which gives you the list of all elements with the class name as "example'. Then you can loop around based on the length of x.
References:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try this:
var input = document.forms[0].querySelectorAll('input[type=text]');
var result = Array.from(input).reduce((r, ele) => {
r[ele.name] = ele.value;
return r;
}, {});
console.log(result);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
If you used something like .. I think it will work. :)
var myObj = {};
var elems = document.getElementsByTagName('input'), i;
for (i in elems) {
myObj[value + i] = myObj[i].value;
}
return from getElementsByTagName is an array of all matching tags. there are some wizard answers in here ha. :)
document.querySelectorAll is made for this.
document.querySelectorAll("form[name='form1'] input[type='text']")
will return all input fields of type text in form1 as HTML nodes.
let elements = document.querySelectorAll("form[name='form1'] input[type='text']");
elements.forEach(e => console.log(e.value));
...logs the values of the input fields. Don't make things harder on yourself by hard coding classes or ID's, and this will allow you to target the input elements you need without additional checks or without fetching every input on the page.
Example:
const values = {};
document.querySelectorAll("form[name='form1'] input[type='text']").forEach(element => values[element.name] = element.value);
console.log(values);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
This is an alternative solution done with jQuery.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
//jQuery solution
const obj = {}
$('#save').click(function(e){
var form = $(this).parent();
var inputs = form.children().not(':input[type=button]');
$.each( inputs, function(){
obj[$(this).attr('name')] = $(this).val();
});
console.log(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>jQuery solution</h2>
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" value="Save">
</form>
JS Solution
//JS Solution
const objs = {}
var button = document.getElementById('savejs');
var form = document.getElementById('formjs');
var element = {};
button.addEventListener('click', function(){
inputs = form.children;
for(i=0; i < inputs.length; i++){
if(inputs[i].name != ""){
objs[inputs[i].name] = inputs[i].value;
}
}
console.log(objs);
})
<h2>JS solution</h2>
<form name="form1" id='formjs'>
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="savejs" value="Save">
</form>
I am adding rows using java script functions by taking input and showing data into input text fields.
I am using this datepicker https://github.com/T00rk/bootstrap-material-datetimepicker.
When I input time the only first value of time is copied into input fields while rest two value are copied but time value is not copied.
<div style="width:90%;margin:auto;">
<h1>Simple example of dynamically adding rows with jQuery</h1>
<form method="post">
<div id="itemRows">
Item quantity: <input type="text" name="add_qty" size="4" /> Item name: <input type="text" name="add_name" />Time:<input type="text" id="time" name="time" />
(This row will not be saved unless you click on "Add row" first)
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time" name="time[]" size="4" value="'+frm.time.value+'" > Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
frm.time.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
When you generate dynamic textbox with id and with date picker so you need to call one function for init datepicker on that text like below
$('input').bootstrapMaterialDatePicker();
function addRow(frm)
{
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time'+rowNum+'" name="time[]" size="4" value="'+frm.time.value+'" > Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
frm.time.value = '';
$('#time'+rowNum).bootstrapMaterialDatePicker();
}
In above function i add one id to time textbox and call bootstrap datepicker to init date on that textbox.
See working demo here
http://plnkr.co/edit/P0ZQsAjDJAXyJGs9kvT3?p=preview
How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>