I am trying to add multiple fields by clicking one plus button. Then I have four arrays for four specific text fields: company, from, to, and year. If I click the button, I will get the four fields. I want to enter values and have the values saved in the four arrays. When I click the button again the same thing should happen.
The array saves only the first value from each field and the other value is null. How can I save all of the values in the arrays?
var company = [];
var from = [];
var to = [];
var year = [];
var scntDiv = $('#addmorefieldexp');
var i = $('#addmorefieldexp p').size() + 1;
/* $('#pexp').live('click', function() */
$("#pexp").click(function(){
$( ' <br><br>'
+'<label for="inputPassword3" class="col-sm-2 control-label">Company Name</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_company[]" value="" id="company">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">From</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_from[]" value="" id="from">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">To</label>'
+'<div class="col-sm-2">'
+'<input type="text" class="form-control" name="field_to[]"value="" id="to">'
+'</div>'
+'<label for="inputPassword3" class="col-sm-1 control-label">Year</label>'
+'<div class="col-sm-1">'
+'<input type="text" class="form-control" name="field_year[]"value="" id="year">'
+'</div>').appendTo(scntDiv);
var add_company = $("input[name$='field_company[]']").val();
company.push(add_company);
var add_from = $("input[name$='field_from[]']").val();
from.push(add_from);
var add_to = $("input[name$='field_to[]']").val();
to.push(add_to);
var add_year = $("input[name$='field_year[]']").val();
year.push(add_year);
console.log(company, from, to, year);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="form-group" id="experience">
<label class="col-sm-2 control-label">Employment Experience</label>
<div class="col-sm-4" id="checkbox" value="">
<input type="radio" name="exp" class="expp" value="Yes">Yes
<input type="radio" name="exp" class="expp" value="No">No
<button class="btn btn-lg btn-sm btn-primary btn-circle" id="pexp"><i class="fa fa-plus"></i>
</button>
</div>
</div>
<div class="form-group text-center" id="addmorefieldexp">
<p>
</p>
</div>
You just need to write a for loop to iterate through all of the input fields, like so:
var companyField = $("input[name$='field_company']");
for (var i;i<companyField.length;i++) {
var companyValue = companyField[i].val();
company.push(companyValue);
}
var fromField = $("input[name$='field_from']");
for (var i;i<fromField.length;i++) {
var fieldValue = fromField[i].val();
from.push(fieldValue);
}
var toField = $("input[name$='field_to']");
for (var i;i<toField.length;i++) {
var toValue = toField[i].val();
to.push(toValue);
}
var yearField = $("input[name$='field_year']");
for (var i;i<yearField.length;i++) {
var yearValue = yearField[i].val();
year.push(yearValue);
}
I is done!!! I have to add this to save value on the array.
var inps = document.getElementsByName('field_company[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
company.push(inp.value);
Related
Codepen https://codepen.io/mehmetmasa-the-selector/pen/RwBQbOr
When I click the button, I add a new field. One of the added fields (radio button) needs to be selected. But since the user can add/delete, I can't give the value value.
HTML Code
<div id="answer">
<div class="form-group d-flex">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap </label>
</div>
<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">
<button class="btn btn-primary ml-3 col-md-1" type="button" id="addAnswer">Yeni Cevap</button>
</div>
</div>
JS Code
$('#addAnswer').on('click', function() {
$('<div class="form-group d-flex">' +
'<div class="form-check">' +
'<label class="form-check-label">' +
'<input class="form-check-input trueAnswer" type="radio" name="trueAnswer">Doğru Cevap' +
'</label>' +
'</div>' +
'<input class="form-control answer" type="text" placeholder="Cevabı Yazınız">' +
'<button class="btn btn-danger ml-3 col-md-1 deleteAnswer" type="button" >Cevabı Sil</button>' +
'</div>').appendTo('#answer');
});
$('#addQuestion').on('click', function() {
let answer = [];
$('#answer .form-group').map(function(i, val) {
if ($(val).find('.answer').val().length > 0)
answer.push({
name: $(val).find('.answer').val(),
trueAnswer: $(val).find('.trueAnswer').val()
});
});
let categoryID = $('#category').val();
let question = $('#question').val();
let questionNo = $('#questionNo').val();
let colorpicker = $('#colorpicker').val();
let formData = new FormData();
formData.append("categoryID", categoryID);
formData.append("question", question);
formData.append("questionNo", questionNo);
formData.append("colorpicker", colorpicker);
for (var i = 0; i < answer.length; i++) {
formData.append('answer' + [i], answer[i].name);
formData.append('answer' + [i], answer[i].trueAnswer);
}
How can I find which answer the user chose?
i'm having trouble going trough making a calculator (sum only) of 5 inputs fields in html/javascript and i can't manage to find what's wrong in my code
i tried messing around with types such as int instead of var and passing the value into parseInt, i somehow managed to have a result like "11111" where it should be like "5" but alongside that case the result is never printed in the innerHTML even after i added the "if not null" condition
Here is my html
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute();">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
and here is my javascript
function ratingCompute()
{
var designValue = document.getElementById("design").value;
var plotValue = document.getElementById("plot").value;
var charValue = document.getElementById("character").value;
var enjoyValue = document.getElementById("enjoyment").value;
var musicValue = document.getElementById("music").value;
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
Any clue?
JavaScript is not a type variable language try using let or const. And here is how you properly parse it. If you did it already then its because of your variable declaration.
let designValue = parseInt(document.getElementById("design").value);
let plotValue = parseInt(document.getElementById("plot").value);
let charValue = parseInt(document.getElementById("character").value);
let enjoyValue = parseInt(document.getElementById("enjoyment").value);
let musicValue = parseInt(document.getElementById("music").value);
In javascript you should use keyword var/let/const instead of int. and you have to convert String type input value to int using parseInt method.
Please check this:
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute()">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
As mentioned by #Joshua Aclan, JavaScript does not have an "int" variable declaration, only "var". Also you have to cast all of the inputs to int or float, because otherwise you are adding strings and the values of input fields are always strings. Also the output is most likely empty because int designValue... produces an error.
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
I have dynamically generated html which are rendered in browser like
var address_details_array = []
// Address details Array
$(".address-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").first().each(function() {
var addressTypeValue = $(this).val();
var addressLine1 =$this.filter("input[type=text]:nth-child(1)").val();
var addressLine2 = $this.filter("input[type=text]:nth-child(2)").val();
var city = $this.filter("input[type=text]:nth-child(3)").val();
var innerAddressArray = {};
innerAddressArray = {
addressTypeValue: addressTypeValue,
addressLine1: addressLine1,
addressLine2: addressLine2,
city: city
};
address_details_array.push(innerAddressArray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dynamic-address-details">
<div id="count-address0" class="address-container"><div class="form-group">
<label class="col-sm-3 control-label">Address Type</label><div class="col-sm-5">
<select name="addrees-line-one0" id="addrees-line-one0" class="form-control"><option value="Physical">Physical</option><option value="Correspondence">Correspondence</option></select></div><button value="count-address0" class="remove-address-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
<div class="form-group"><label class="col-sm-3 control-label">Address Line 1</label><div class="col-sm-5"><input type="text" name="addrees-line-one0" id="addrees-line-one0" class="form-control"></div></div>
<div class="form-group"><label class="col-sm-3 control-label">Address Line 2</label><div class="col-sm-5"><input type="text" name="addrees-line-two0" id="addrees-line-two0" class="form-control"></div></div>
<div class="form-group"><label class="col-sm-3 control-label">City</label><div class="col-sm-5"><input type="text" name="city0" id="city0" class="form-control"></div></div>
</div>
<div id="count-address1" class="address-container"><div class="form-group">
<label class="col-sm-3 control-label">Address Type</label>
...
...
</div>
</div>
It is showing undefined values in addressLine1, addressLine2,city. Please help me in fetching their values from above html generated dynamically.
Use find instead of filter and eq instead of nth-child
var addressLine1 = $this.find("input[type=text]").eq(0).val();
var addressLine2 = $this.find("input[type=text]").eq(1).val();
var city = $this.find("input[type=text]").eq(2).val();
Demo
var address_details_array = [];
$(".address-container").each(function(i, obj) {
var $this = $(this);
$this.find("select").first().each(function() {
var addressTypeValue = $(this).val();
console.log( $this.find("input").length );
var addressLine1 = $this.find("input[type=text]").eq(0).val();
var addressLine2 = $this.find("input[type=text]").eq(1).val();
var city = $this.find("input[type=text]").eq(2).val();
var innerAddressArray = {};
innerAddressArray = {
addressTypeValue: addressTypeValue,
addressLine1: addressLine1,
addressLine2: addressLine2,
city: city
};
address_details_array.push(innerAddressArray);
});
});
console.log( address_details_array );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="count-address0" class="address-container">
<div class="form-group">
<label class="col-sm-3 control-label">Address Type</label>
<div class="col-sm-5">
<select name="addrees-line-one0" id="addrees-line-one0" class="form-control"><option value="Physical">Physical</option><option value="Correspondence">Correspondence</option></select></div><button value="count-address0" class="remove-address-field btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
<div class="form-group"><label class="col-sm-3 control-label">Address Line 1</label>
<div class="col-sm-5"><input type="text" name="addrees-line-one0" id="addrees-line-one0" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-3 control-label">Address Line 2</label>
<div class="col-sm-5"><input type="text" name="addrees-line-two0" id="addrees-line-two0" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-3 control-label">City</label>
<div class="col-sm-5"><input type="text" name="city0" id="city0" class="form-control"></div>
</div>
</div>
nth-child wouldn't work since in any given HTML element there's only one input and that is why it is always the 1st i.e nth-child(1).
Since you already have given the IDs to the input elements you can reference them by its ID, or even name and get the values.
var addressTypeValue = $(this).val();
var addressLine1 =$this.filter("#addrees-line-one0").val();
var addressLine2 = $this.filter("#addrees-line-two0").val();
var city = $this.filter("#city0").val();
This is as simple as this.
var address_details_array = []
$(".address-container").each(function(i, obj) {
var $this = $(this);
var addressLine1 =$this.find("#addrees-line-one"+i).val();
var addressLine2 = $this.find("#addrees-line-two"+i).val();
var city = $this.find("#city"+i).val();
$this.find("select").first().each(function() {
var addressTypeValue = $(this).val();
var innerAddressArray = {};
innerAddressArray = {
addressTypeValue: addressTypeValue,
addressLine1: addressLine1,
addressLine2: addressLine2,
city: city
};
address_details_array.push(innerAddressArray);
});
});
Put above code before $this.find("select").first().each(function() { Because is unnecessarily executing in select loop, which I believe no use.
i have a single page which is divided into two sections.So at first first section is seen and we need to fill the inputs value and when we click go to next page button then the first section is now hidden and second section is shown.Then only we can submit the form.
Now what i want is that in the first section, i have four inputs like shown below
<div class="room_details_first col-md-12" id="first_order">
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]"/>
</div>
</div>
Now by using jquery i have append the inputs and the code is shown below
function add_others_order(){
var output="";
output+= '<div class="room_details_first col-md-12" id="first_order">';
output+='<div class="col-md-3"><input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/></div>';
output+='<div class="col-md-3"> <input type="text" placeholder="Hotel Name" name="others_hotel[]"/> </div>';
output+='<div class="col-md-3"><input type="text" placeholder="Hotel price" name="others_hotel_price[]"/></div>';
output+='<div class="col-md-2"> <input type="text" placeholder="Customer Price" name="others_client_price[]"/></div>';
output+='<div class="col-md-1" ><i class="fa fa-remove"></i></div>';
output+='</div>';
$('#first_order').after(output);
}
now what i need is i need to save the inputs value before submitting and list it in second section of the page.i have tried to do it but i am failed many times. And i have also found similar answers which is given below
Display the data entered in a form before submitting the form
Guys i need help.
Here is what you want, you will get all input's value and you can do
what ever you want with it.
function nextStep() {
var allFields = document.getElementsByTagName("input");
//console.log(allFields);
for (var index in allFields) {
console.log('name : '+allFields[index].name);
if (allFields[index].type == "text") { // you can change condition by name instead of type
if (allFields.hasOwnProperty(index)) {
var attr = allFields[index];
console.log(attr.value)
}
}
}
}
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]" />
</div>
<input type="button" onclick="nextStep()" value="Next step">
I think this is what you want, or as close to what you need, I add an Id attribute so you can do add/remove:
var stored_data = [];
stored_data.total = 0;
$('#dummy').on('click', function(){
var obj = {
id: stored_data.length,
food: food.value,
hotel_name: hotel_name.value,
hotel_price: hotel_price.value,
customer_price: customer_price.value
};
stored_data.push(obj);
stored_data.total += parseInt(obj.customer_price);
//$('#first_section').hide();
var output = '<div class="room_details_first col-md-12" id="first_order">';
output += '<div>Order ' + obj.id + '</div>';
output += '<div class="col-md-3">Food: ' + obj.food + '</div>';
output += '<div class="col-md-3">Hotel Name: ' + obj.hotel_name + '</div>';
output += '<div class="col-md-3">Hotel Price' + obj.hotel_price + '</div>';
output += '<div class="col-md-2">Customer Price' + obj.customer_price + '</div>';
output += '<div class="col-md-1" ><i class="fa fa-remove"></i></div> ';
$('#new_section').append(output);
$('#total').text(stored_data.total);
});
https://jsfiddle.net/5uka65tx/2/
Here's a way to do it by using clone() on the whole first order and do some modifications to add the link and change duplicate ID and last item column class.
First use serializeArray() to get the values to store
var values = $('#first_order :input').serializeArray();
console.log(values);
then clone , modify and insert
var link = '<div class="col-md-1" ><i class="fa fa-remove"></i>LINK</div>';
// clone first order and update ID
var $first = $('#first_order').clone().attr('id', 'first-order_2');
// modify column on last one and add the link
$first.children(':last').toggleClass('col-md-2 col-md-3').after(link);
// insert in second position
$('#second').append($first)
DEMO
By taking reference of Jigar7521, i tried to do the following way
var allFields = document.getElementsByClassName("others_order");
var others_total_price='0';
var others_food_items=new Array();
var others_hotel_name=new Array();
var others_hotel_price=new Array();
var others_client_price=new Array();
//var others['food_items'] = new Array();
var ficounter=0;
var hcounter=0;
var hpcounter=0;
var cpcounter=0;
Array.prototype.forEach.call(allFields, function(el) {
if(el.name=='others_client_price[]'){
others_client_price[cpcounter]=el.value;
cpcounter++;
others_total_price=parseFloat(others_total_price)+parseFloat(el.value);
}
if(el.name=='others_food_items[]'){
others_food_items[ficounter]=el.value;
ficounter++;
}
if(el.name=='others_hotel[]'){
others_hotel_name[hcounter]=el.value;
hcounter++;
}
if(el.name=='others_hotel_price[]'){
others_hotel_price[hpcounter]=el.value;
hcounter++;
}
});
$('#others_total_price').val(others_total_price);
var others_output="<h4>Others Order</h4>";
for(var i=0;i<=ficounter;i++){
others_output+='<div ><div class="col-md-12"><div class="col-md-3">'+others_food_items[i]+'</div><div class="col-md-3">'+others_hotel_name[i]+'</div><div class="col-md-3">'+others_hotel_price[i]+'</div><div class="col-md-3"> '+others_client_price[i]+'</div></div></div>';
}
$('#others_id').html(others_output);
it worked but i get errors like undefined
i tried to console.log every array and i got what i did not have expected
I created dynamic adding fields to form but I have problem with color input:
Standard inputs are added normally but input with color on first click is not adding and on next click 'Add field' is adding next fields with color to all inputs/.
Here is my code:
HTML:
<div class="form-group" id="propositionsFields">
<label class="col-md-4 control-label">Options</label>
<div class="row">
<div class="col-8">
<input class="form-control propositionField" name="proposition[]" type="text" />
</div>
<div class="col-2">
<input type="text" class="form-control jscolor {onFineChange:'updateColor(this)'}" />
<input type="hidden" class="color-picker" value="" />
</div>
<div class="col-2">
<button class="add-proposition-field propositionManage">Add field</button>
</div>
</div>
</div>
JS:
$(document).ready(function() {
var addField = $(".add-proposition-field");
var removeField = $('.remove-proposition-field');
addField.click(function(e) {
var rodzic = $('.colorInput');
e.preventDefault();
var i = $('.propositionField').size();
var color = 'FF0000';
var input = document.createElement("input");
input.className = "form-control";
input.setAttribute("value", color);
input.setAttribute("type", 'text');
var picker = new jscolor(input);
var newField = '<div class="row"><div class="col-8"><input autocomplete="off" class="form-control" name="proposition[]" type="text" placeholder="Field No."/></div><div class="col-2 colorInput"></div><div class="col-2"><button class="remove-proposition-field propositionManage">Usuń pole</button></div></div>';
i++;
rodzic.append(input);
$(" #propositionsFields ").append(newField);
});
$('body').on('click', '.remove-proposition-field', function() {
$(this).parent('div').parent('div').remove();
});
});
Demo: https://jsfiddle.net/k95detc8/
The issue if because you add the element before is exist. And the colorInput content is added to all colorInput class. I have remove your first element and add last parameter for add only in the last element
$(document).ready(function() {
var addField = $(".add-proposition-field");
var removeField = $('.remove-proposition-field');
addField.click(function(e) {
e.preventDefault();
var i = $('.propositionField').size();
var color = getRandomColor();
var input = document.createElement("input");
input.className = "form-control";
input.setAttribute("value", color);
input.setAttribute("type", 'text');
var picker = new jscolor(input);
var newField = '<div class="row"><div class="col-8"><input autocomplete="off" class="form-control" name="proposition[]" type="text" placeholder="Field No."/></div><div class="col-2 colorInput"></div><div class="col-2"><button class="remove-proposition-field propositionManage">Usuń pole</button></div></div>';
i++;
$(" #propositionsFields ").append(newField);
$('.colorInput:last').append(input);
});
$('body').on('click', '.remove-proposition-field', function() {
$(this).parent('div').parent('div').remove();
});
});
function updateColor(jscolor) {
$('.color-picker').val(jscolor);
$(this).val(jscolor);
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
div{
width:100% !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="http://beta.leonardo.pl/afrisoexpert/public/css/fluidable.css" rel="stylesheet"/>
<div class="form-group" id="propositionsFields" >
<label class="col-md-4 control-label">Options</label>
<div class="row">
<div class="col-8">
<input class="form-control propositionField" name="proposition[]" type="text" />
</div>
<div class="col-2">
<input type="text" class="form-control jscolor {onFineChange:'updateColor(this)'}" />
<input type="hidden" class="color-picker" value="" />
</div>
<!-- /.col-2 -->
<div class="col-2">
<button class="add-proposition-field propositionManage">Add field</button>
</div>
<!-- /.col-2 -->
</div>
<!-- /.row -->
</div>
<!-- /.form-group -->