how to create the dynamic form fields in javascript - javascript

i want to create a dynamic form like the user needs to add attribute but those attribute not defined previously he can add as many he can for example he created a dress he want to add attribute like size he will click on add attribuute that will generate an html i have did this but there i need to insert some variable so i can change the name of the attributes
var i =1;
function add_fields() {
var emptydiv = document.createElement('div')
emptydiv.innerHTML = '<div class="col-12 col-md-6"><div class="group"><input type="text" name="`{i}`" id="Royalties" required><span class="highlight"></span><span class="bar"></span><label>Attributes</label></div></div><div class="col-12 col-md-6"><div class="group"><input type="text" name="Size" id="Size" required><span class="highlight"></span><span class="bar"></span><label>value</label></div></div></div>'
document.getElementById('addable').appendChild(emptydiv);
i++;
console.log(i)
return emptydiv;
// console.log("Hello world")
}
what i want to change the name fields in this html by the variable i

I believe this is what you are trying to accomplish.
I changed regular single quotes into a template literal
var i =1;
function add_fields() {
var emptydiv = document.createElement('div')
emptydiv.innerHTML = `<div class="col-12 col-md-6"><div class="group"><input type="text" name="${i}" required><span class="highlight"></span><span class="bar"></span><label>Attributes</label></div></div><div class="col-12 col-md-6"><div class="group"><input type="text" name="Size" id="Size" required><span class="highlight"></span><span class="bar"></span><label>value</label></div></div></div>`
document.getElementById('addable').appendChild(emptydiv);
i++;
console.log(i)
return emptydiv;
// console.log("Hello world")
}
add_fields();
<div id="addable"></div>

Related

How will i show my data output inside an input element using Jquery

Here is my Javascript code:
$('#sb_add_ctrl').click(function() {
var value = $('#sel_control_num').val();
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function(match, n) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
$('#parent')[0].innerHTML += '<br>' + value;
}
})
Here is my HTML code:
<div><label> Control Number </label>
<input name="get_control_num" style="text-transform:uppercase"
class="form-control" id="sel_control_num" readonly>
</div>
<div class="form-group">
<label> Quantity </label>
<input class="form-control" name="quantity" type="number"
/>
<br>
<button type="button" id="sb_add_ctrl" class="btn btn-primary"> Add
Control Number </button>
</div>
<div class="form-group" id="parent"></div>
What I want to do is get the existing class of the input and show the data that is in innerHTML into an input element .I can't think of a proper solution cause I am still a beginner in javascript/jquery, I tried the other methods in jquery but still it doesn't work thanks for the help

Modify input names in childnodes with JavaScript

I need help extending this JavaScript (borrowed from https://www.quirksmode.org/dom/domform.html):
var appCounter = 0;
function anotherApp() {
appCounter = appCounter + 1;
var newAppField = document.getElementById("keyApp").cloneNode(true);
newAppField.id = '';
newAppField.style.display = 'block';
var newApp = newAppField.childNodes;
for (var i = 0; i < newApp.length; i++) {
var theName = newApp[i].name
if (theName) {
newApp[i].name = theName + appCounter;
}
}
var insertApp = document.getElementById('keyApp');
insertApp.parentNode.insertBefore(newAppField, insertApp);
document.getElementById('appCount').value = appCounter
}
This works fine when element in my form is:
<div id="keyApp" style="display:none">
<input type="text" name="application" id="application">
<input type="text" name="usage" id="usage">
<\div>
But when I add div's around the inputs (bootstrap styling reasons) I loose the ability to update the input names:
<div id="keyApp" style="display:none">
<div class="col-md-2">
<input type="text" name="application" id="application">
</div>
<div class="col-md-2">
<input type="text" name="usage" id="usage">
</div>
<\div>
How do I extend the script to modify the input names in these new div's?
Since there is now another layer, you need to get newApp[i].childNodes[0] now in order to get the actual input elements.
newApp now holds a list of the div elements with col-md-2 styling, and you need to get the children inside of these div elements.

Array of html inputs

I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/

select id that created dynamically in jquery

I wrote the below jQuery code, in this code when I click on #addbtn 2 text-box with this code below is created
var i = 2;
/* button #add_btn */
$(document).on("click", "#add_btn", function(evt) {
$('.add_checkbox').append("<input type='checkbox' id=foodcheckbox_" + i + " style='margin-bottom:20px;'><br/>");
$(".add_food").append("<input class='wide-control form-control default input-sm foodha' type='text' placeholder='Food' id=food_input" + i + " style='margin-bottom:5px;'>");
$(".add_price").append("<input class='wide-control form-control default input-sm priceha' type='text' placeholder='Price' id='price_input" + i + "' style='margin-bottom:5px;'>");
i++;
});
This code works fine, but when I want to select text-boxes that are added with the above code to get the content of them the selector by id isn't working, below is the code that I use to get value of these text-boxes:
/* button Submit */
$(document).on("click", ".uib_w_60", function(evt) {
var foodid = [];
var priceid = [];
/* your code goes here */
/* first I get id of .foodha class */
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
/* second I get id of .priceha class */
$(".priceha").each(function() {
var pID = $(this).prop("id");
priceid.push(pID);
});
var newfoodpriceid = [];
/* here I dont know why the Id that gotten save
twice in array, for example save with this pattern
[food_input2, food_input3, food_input2, food_input3]
and to prevent this I use a trick and save it in another
array with the code below: */
for (var c = 0; c < priceid.length / 2; c++) {
newfoodpriceid.push({
'foodid': foodid[c],
'priceid': priceid[c]
});
}
/* then I want to get value of text box with exact
id that I select with jQuery selector but the
selector isn't working and the returned value
is nothing but I enter a value in text box that
have below id: */
var pr = $("#" + newfoodpriceid[0].priceid).val();
$("p").text(pr);
});
I explain anything that I think you need to know about what I want to do.
HTML code before I click on addbtn to add text-boxes:
<div class="grid grid-pad urow uib_row_42 row-height-42" data-uib="layout/row" data-ver="0">
<div class="col uib_col_46 col-0_1-12_1-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col center">
<div class="add_checkbox" style="margin-top:5px"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_48 col-0_6-12_6-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_food"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_47 col-0_5-12_5-5" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_price"></div>
<span class="uib_shim"></span>
</div>
</div>
<span class="uib_shim"></span>
</div>
And that HTML code after click on "add btn" twice
<div class="add_food">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input3" style="margin-bottom:5px;">
</div>
<div class="add_price">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input3" style="margin-bottom:5px;">
</div>
As you can see the text-box with the id that I want is generated fine, but I can't select it with using its id.
The only problem I see in your code is that once the page has run you must re-call the "each" function from jquery. When this "loop" is performed there are no "foodha" or "priceha" class cointaining elements. You could put the
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
in a sleep loop or in a js function which you would call later.Like this:
setTimeout(function(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
},1000); //for a second delay
or
function call_after_creating(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
}

how to multiply input value of each div with same id

I have several line of div with same id, i would like to multiply two input value of each div and display result in third input after changing value of val1 input or val2 input
html
<div class="uk-width-medium-9-10" id="commandligne">
<div class="uk-grid uk-grid-small" data-uk-grid-margin>
<div class="uk-width-medium-2-10">
<label for="inv1">P.U. (€)</label>
<input type="text" name="prix-item[]" class="md-input val1" id="inv1"/>
</div>
<div class="uk-width-medium-2-10">
<label for="inv2">Qté (H)</label>
<input type="text" name="qte-item[]" class="md-input val2" id="inv2" />
</div>
<div class="uk-width-medium-2-10">
<label for="inv3">Total(€)</label>
<input type="text" name="total-item[]" class="md-input val3" value="0" id="inv3" readonly/>
</div>
</div>
</div>
My JS that doesnt work at all
$(document).ready(function () {
$("#commandligne input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("div#commandligne").each(function () {
// get the values from this div:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.val3',this).val($total);
});
}
});
Nothing happen when i change value of 2 input, then i have 0 error .
Here Jsfiddle
https://jsfiddle.net/a66bgddu/1/
Consider Usage of id Attributes
You are currently appending multiple elements with the same ID, which is not valid. id attributes by definition must be unique :
The id global attribute defines a unique identifier (ID) which must be
unique in the whole document. Its purpose is to identify the element
when linking (using a fragment identifier), scripting, or styling
(with CSS).
If you need to target multiple elements, then consider using classes or data-* attributes to select them. Alternatively, you could track the number of "rows" and append the number after each ID and use the jQuery "starts-with" selector to target them:
Ensuring Dynamic Elements Are Targeted
Currently, your event handlers do not target any elements that may be added to the DOM in the future. You may want to consider using the .on() function handle wiring up your events, which will target those that currently exist in the DOM and those that may be added in the future :
// Example using a class "command-row" as opposed to Id attributes
$(document).on('keyup',"div.command-row input",multInputs);
Parse Your Values
Since you are performing arithmetical operations on your values, you'll want to ensure that you are actually parsing the contents of your <input> elements as opposed to simply retrieving string versions of their values. You can do this using the parseInt() function :
// Parse your values
var $val1 = parseInt($('.val1', this).val());
var $val2 = parseInt($('.val2', this).val());
// Get your total
var $total = $val1 * $val2
// Set your value
$('.val3',this).val($total);
Example: Putting It All Together
document.getElementById("test").onclick = function() {
var ok = true;
if (ok === true) {
var html = [
'<br/><br/>',
'<div class="uk-grid uk-margin-bottom" data-uk-grid-margin>',
'<div class="uk-width-medium-9-10 command-row">',
'<div class="uk-grid uk-grid-small" data-uk-grid-margin>',
'<div class="uk-width-medium-2-10">',
'<label for="inv1">P.U. (€)</label>',
'<input type="text" name="prix-item[]" class="md-input val1" />',
'</div>',
'<div class="uk-width-medium-2-10">',
'<label for="inv2">Qté (H)</label>',
'<input type="text" name="qte-item[]" class="md-input val2" />',
'</div>',
'<div class="uk-width-medium-2-10">',
'<label for="inv3">Total(€)</label>',
'<input type="text" name="total-item[]" class="md-input val3" value="0" readonly/>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
var div = document.createElement('div');
div.innerHTML = html;
document.getElementById('testa').appendChild(div);
}
};
$(document).ready(function() {
$(document).on('keyup', "div.command-row input", multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("div.command-row").each(function() {
// get the values from this div:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.val3', this).val($total);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testa">
<div class="uk-grid uk-margin-bottom" data-uk-grid-margin>
<div class="uk-width-medium-9-10 command-row">
<div class="uk-grid uk-grid-small" data-uk-grid-margin>
<div class="uk-width-medium-2-10">
<label for="inv1">P.U. (€)</label>
<input type="text" name="prix-item[]" class="md-input val1" />
</div>
<div class="uk-width-medium-2-10">
<label for="inv2">Qté (H)</label>
<input type="text" name="qte-item[]" class="md-input val2" />
</div>
<div class="uk-width-medium-2-10">
<label for="inv3">Total(€)</label>
<input type="text" name="total-item[]" class="md-input val3" value="0" readonly/>
</div>
</div>
</div>
</div>
</div>
<div id="test" class="uk-grid" data-uk-grid-margin>
<div class="uk-width-1-1">
<div id="form_invoice_services"></div>
<div class="uk-text-center uk-margin-medium-top uk-margin-bottom">
Ajouter une ligne
</div>
</div>
</div>
Yeah, the fundamental issue that you are facing is that id attributes MUST be unique on a page in HTML. Browsers are flexible about this and don't really complain about it if you have duplicates, but both JavaScript and jQuery are not.
In both cases (getElementById in JavaScript and $("#aDuplicatedId") in jQuery), the logic will only capture a single DOM node/jQuery object . . . specifically the first one that it encounters in the DOM that has the specified id.
To do what you are trying to do, consider using a common class that you can select on. This will capture all instances and allow you to iterate through using your existing code.

Categories