Javascript function for form created using Javascript - javascript

I have a script which adds a new form when a button is clicked to a HTML page with the code as following:
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("Max number of forms, " + counter );
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<form name='frmMain' action='prelucrare.php' method='POST'><div class='slot' id='dynamicInput' align='center'> Masina " + (counter +1 ) + "<table border='1'><tr><td align='right'><label for='marca'>Marca:</label></td><td colspan='2' align='left'>"
+ "<select id='marc' name='marc'><option selected value=''></option>"
+ "<tr><td align='right'><label for='motorizare1'> Motorizare:</label></td> <td><input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id=motor1 oninput='outputUpdate1(value)'></td><td><output for=motorizare1 id=moto1>2</output></td></tr>"
+ "</div></form>"
;
}
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
<input type="button" value="Adauga" onClick="addInput('dynamicInput');">
And I have the script bellow which changes the value from the slider.
<script>
function outputUpdate1(mot1) {
document.querySelector('#moto1').innerHTML = mot1;
}
</script>
My problem is that the JS code only changes the input for the first form, even if the slider is activated from another form. In short, the slider should return the value in the form from which it is activate; not only in the first form added.
Thank you!

Going along with my comment, the problem is stemming from the id value being the same across all of your output elements (moto1). You've actually got all the variables you need to make them unique since you're tracking a count of the number of forms on the page (your counter variable). You can use this in place of your current output HTML:
"<input type='range' name='motorizare1[]Input' min='0.6' max='5' step='0.1' value=2 id='motor_" + counter + "' oninput='outputUpdate1(value)'/>"
"<output for=motorizare1 id='moto_" + counter + "'>"
You can update your function to parse out the correct index for the output you want to update since they should be in sync if you use the HTML above:
function outputUpdate1(mot) {
// Get the counter part of the range element's id
var index = mot.id.split('_')[1];
document.querySelector('#moto_' + index).innerHTML = mot;
}
You may need to make some tweaks to code you haven't provided in the question, but that's one way of making the id values unique and how to access them without knowing the exact id ahead of time.

Related

How to make automatic input line appender in js?

I'm having an HTML page with an input line and a submit button.
I'm wanting to automatically generate a new line under the line if we change the first line content.
Before searching for this, I just made a second button named "Add new line" (explicit).
HTML part
print '<input type="button" id="addLineButton" value="Ajouter ligne"/>';
print '<input type="submit" id="valider" value="Rechercher"/>';
JS part
$("#addLineButton").click(function(e){
e.preventDefault();
var newLine = "";
document.getElementById("nbLines").textContent = Number(document.getElementById("nbLines").textContent) + 1;
var nbLines = Number(document.getElementById("nbLines").textContent);
newLine += "<input type='text' id='line"+nbLines+"' placeholder='Ref article'/><input type='number' id='qty"+nbLines+"' placeholder='Qté étiquettes'/><br>"
$("#zoneOF").append(newLine);
});
$("#zoneOF") is a div, and nbLines is a label which is used to count how many lines we already have.
I'm then searching (but not founding because I don't know how to formulate it clearly) what can I do to remove my addLineButton and automate the line adding (surely with on change event).
I wouldn't be surprised if you didn't understood sthg, then don't hesitate to ask me to reformulate.
Thank you in advance.
Ok I resolved it, by simply making my code recursive.
$(document).ready(function(){
var newLine = "";
document.getElementById("nbLines").textContent = Number(document.getElementById("nbLines").textContent) + 1;
var nbLines = Number(document.getElementById("nbLines").textContent);
newLine += "<input type='text' id='line"+nbLines+"' placeholder='Ref article'/><input type='number' id='qty"+nbLines+"' placeholder='Qté étiquettes'/><br>"
$("#zoneOF").append(newLine);
$('#line'+nbLines).on('change', function() {
setNewLine();
});
function setNewLine() {
var newLine = "";
document.getElementById("nbLines").textContent = Number(document.getElementById("nbLines").textContent) + 1;
var nbLines = Number(document.getElementById("nbLines").textContent);
newLine += "<input type='text' id='line"+nbLines+"' placeholder='Ref article'/><input type='number' id='qty"+nbLines+"' placeholder='Qté étiquettes'/><br>"
$("#zoneOF").append(newLine);
$('#line'+nbLines).on('change', function() {
setNewLine();
});
}
I make a new line at the document creation, and I put the on change event on it. The on change calls a function which creates a new line, and the function calls herself when the on change event is triggered on the new line.

Adding an additional row of HTML form inputs using Javascript

I am attempting to dynamically add a new row of HTML form inputs (a new line which includes 6 inputs, namely, (Type(dropdown), Length, Width, Height, Weight and Quantity) into an existing "View" HTML form using Javascript.
The current HTML form inputs are then accessed in my controller file via PHP $_POST requests. This works fine by retrieving the "name" field in the HTML form.
So, a user completes the first line, which id for the shipment of one parcel, and they want to add a second parcel, so, they click on an add(or remove) to add or remove an extra line of inputs.
I have the code working without adding the second row. If you leave the form at default, all the $variables are retrieved for the controller to act on them.
I managed to get some Javascript code off the net which adds the second part of the input form correctly, but, I assumed the code would increment the "name" field so that the first shipment would be name=length and the second shipment would be name=length2. The code does need Bootstrap as well to work correctly.
I have PHP, HTML skills, but limited Javascript skills, hence my request please.
$(document).ready(function() {
var counter = 0;
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
<!--cols += '<td><select class="form-control col-md-8" id="packaging_type" name="packaging_type' + counter + '"/></td>';-->
cols += '<td><input type="text" class="form-control" name="length' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="width' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="height' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="weight' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="quantity' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function() {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
Ultimately, once I have clicked on the Add Row and entered all of the inputs, I would want the script to numerically increment the "name" input of the HTML form and then be able access them via PHP $_POST.
If there is a better way of doing it, I am open to suggestions.
This won't work anyway, I would suggest using a guid instead of a counter since deleting a row before the last would cause the counter to set itself to the same number as the current last row.
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(3);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
I have managed to find a script that with customisation appears that it will resolve my problem. I will post the outcome once completed so that it may help any future users. The script link is found at :- https://www.jqueryscript.net/demo/Duplicate-Input-Fields-jQuery-Repeatable/
Basically what this script does it it allows you to duplicate DIVs in a table or form, and increments the indexes, "name" "id" etc.
I will be using it to dynamically add additional "inputs" on a form.

getElementById() in for loop to retrieve input values

In a for loop, I am using getElementById() to retrieve several input values in javascript.
First I made a bunch of input boxes and set the different id's using a for loop.
Now I'm using a second for loop to reference those id's and retrieve their input values.
Code:
for (i=0;i<products.length;i++){
var display;
display ="<input type='number' id="+products[i][0]+" onchange=myFunction()>";
document.write(display);
}
document.write("<p id=demo></p>");
function myFunction() {
var totalVeg=0;
for (j=0;j<products.length;j++){
amount = document.getElementById(products[j][0]).value;
totalVeg += amount;
}
document.getElementById("demo").innerHTML = "You selected: " + totalVeg;
}
</script>
Specifically I'm having trouble with this part:
amount = document.getElementById(products[j][0]).value;
If I reference a specific input, like products[0][0], the value will be found. It is only when I try to reference an id using the "j" variable then the code stops working.
I've read through some of the other questions and answers on here but none are exactly what I want.
Thanks!
<script type="text/javascript">
var products = ["Saab","Volvo","BMW"];
for (i=0;i<3;i++)
{
var display;
display ="<input type='number' id='"+products[i]+"'onchange=myFunction(this.id)>";
document.write(display);
}
document.write("<p id=demo></p>");
var totalVeg=0;
function myFunction(_this) {
amount = parseInt(document.getElementById(_this).value);
totalVeg += amount;
document.getElementById("demo").innerHTML = "You selected: " + totalVeg;
}
</script>
You can take it as a reference. Hope it helps.
seem you don't have the quote around the id andbthen the id is not properly defined try this way
for (i=0;i<products.length;i++){
var display;
display ="<input type='number' id='"+products[i][0]+"' onchange=myFunction()>";
document.write(display);
}

php won't post value to email

I have added a button onclick function to a web form, so that onClick new input text field is created. However when the forms posts to email, Quote_Num value isn't posted - it just says "Array"
JS
var counter = 1;
var limit = 8;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Quote Number " + (counter + 1) + " <p><input type='text' name='Quote_Num[]' /></p>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
HTML
<div id="dynamicInput">
Quote Number
<p><input type="text" id="Quote_Num" name="Quote_Num[]" class="required" /> *</p>
</div>
<p><button type="button" value="Add another text input" onClick="addInput('dynamicInput');">Add Quote Number</button></p>
PHP
<?php
$Quote_Num = $_POST["Quote_Num"];
foreach ($Quote_Num as $eachInput)
{
echo $eachInput . "<br>";
}
?>
Anyone with my experience with PHP help me get the form to post value of Quote_Num?
The variable $Quote_Num set with $Quote_Num = $_POST["Quote_Num"]; is an array, as you are submitting more then one values values from your HTML form by setting name equal to Quote_Num[].
If you echo an Array in PHP, It will give an Notice, and print 'Array'.
If you want all of the values of the array $Quote_Num you can use implode on Array. For example implode(", ", $Quote_Num) will return comma separated list of all values in the array as String.
You may also print the whole array by using var_dump or print_r.
I hope, I got your question and it helps.

jQuery onclick add textbox value to div using the ID's

I am trying to add some textbox value to some other divs.
What I'd like to obtain is somthing like this:
textbox id = "text-box-name-1" ----> div id = "div-name-1"
textbox id = "text-box-name-2" ----> div id = "div-name-2"
textbox id = "text-box-name-3" ----> div id = "div-name-3"
and so on....
How can i do this? mind that the number of divs and textboxes are dynamically generated.!
Any suggestion will be really appreciated.
Thanks
EDIT
function test() {
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
for (var i = 0; i < rooms; i++) {
$("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
};
if ($('.housecontainer').find('.appendeddiv').length) {
$("#buttonaddrooms").hide();
}
};
i have already this code that allows me to create as many divs and textboxes as i type inside the textbox as value.
Now, i want be able to set, for example as div title, what the user type inside the textbox, and the only way that i've thought till now is using the id that are dynamically generated by the code that i already have.
Thanks for editing the post...
I would suggest first to add one class as an identifier to the Textbox and Div so we can attach event with the help of jQuery
$("<div class='appendeddiv targetDiv_"+ roomcounter +"'>Room-" + roomcounter + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' lang='textInput' class='targetText_"+ roomcounter +"'></div></br>").appendTo(".infoncontainer");
After that following script will do the trick :)
<script type='text/javascript>
$(function(){
$("input.textInput").on("keyup",function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
});
</script>
As per your fiddle If you want to update value mannualy onclick of any button then write this method.
<script type='text/javascript'>
function update(){
$("input.textInput").each(function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
}
</script>

Categories