I have been trying to set up a kind of search engine connected to an API. It takes the user input and gives back the information from the API. In the future there should be a "dynamic" amount of input fields but for the moment I am working with a fixed amount of five. The loop takes the amount of fields and calls the API that amount of times with that input.
I tried placing a constant (i.e. 5) in the loop but still, the funny part is that with 3 it of course calls the app three times but outputs 6 fields, and with 2 it calls the API 2 times but outputs three rows so it seems that it does not obey the loop but something else. Meanwhile in the console (with log) I can see that the API is properly called only the times defined by the loop so I believe something goes wrong at the $.getJSON level
The problem is at the end a table is created with 15 rows instead of the expected 5 (one row for every input). Why do you think this is happening?
Thanks in advance
<form name="inputform" method="get" width="50">
<input type="text" name="field0" id="field0" size="50">
<input type="text" name="field1" id="field1" size="50">
<input type="text" name="field2" id="field2" size="50">
<input type="text" name="field3" id="field3" size="50">
<input type="text" name="field4" id="field4" size="50">
</form>
<table id="table">
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Preference</th>
</tr>
</table>
<input id="getInfo" type="button" value="Submit" /><br/>
var customURL = "http://apitest.com/test/";
var customURL1 = '';
$('#getInfo').click(function() {
$('#table tr').not(':first').remove();
var fields = document.getElementsByTagName('input');
var table = document.getElementById('table');
if (localStorage.myJSON !== undefined) {
var myJSON = JSON.parse(localStorage.myJSON);
}
var html = '';
for (var i = 0; i < elements.length - 1; i++) {
customURL1 = customURL + document.getElementById('field' + i + '').value;
console.log(customURL1);
$.getJSON(customURL1, function(data) {
console.log(data);
html += '<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>';
$('#table tr').first().after(html);
Each time you get an AJAX response, you're appending the response to the html variable, and then adding that after the first row of the table. Since the html variable already contains the results from the previous responses, and they were insert into the table already, you get duplicates.
Instead of concatenating the new row to html, just insert the new row directly into the table.
$.getJSON(customURL1, function(data) {
console.log(data);
$('#table tr').first().after('<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>');
Related
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.
I am trying to calculate a ticket total based on user input on a form using 2 dimensional names. I have been searching for 2 days on how to pull all the values at once from each key in the input field names.
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
When the user enters the price in the corresponding area, the total for the whole order needs to be calculated and displayed at the bottom of the screen using javascript / jQuery.
Here is the function :
function calculate_ticket(){
var total = 0;
var data = $("input[name^='service[]']").serializeArray();
$.each(data, function(i, field){
$("#ticket_total").append(field.name + ":" + field.value + "<br />"); // for debugging.
});
console.debug(data);
$('#ticket_price').html("$" + total.toFixed(2));
}
What I am hoping to do is pull all the data from each key at once and simply multiply the 'price' by the 'qty' then add that to the 'ticket_price'. The form 'service' input area can have and unlimited number of entries.
I figured a way to do this finally :)
I switched around the name dimension from service[]['qty'] to service['qty'][] and used .serializeArray() on both qty and price. Here is the function :
function calculate_ticket(){
var total = 0;
var price = $("input[name^='service[\\'price\\']']").serializeArray();
var qty = $("input[name^='service[\\'qty\\']']").serializeArray();
$.each(price, function(i, field){
total += qty[i].value * field.value;
});
$('#ticket_price').html("$" + total.toFixed(2));
}
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.
I am appending a <td> having an input text to a row. I want to get the value of this textbox and use it in another function.
Below is the code snippet :
row.append($('<td ><input type="text" value=' + item.Marks + ' size="10px" class="marks" id="txtmarks" maxlength="3"/></td>'));
Thanks in advance.
Split it in two statements:
var input = $("<input type="text" size="10px" class="marks" id="txtmarks" maxlength="3"/>").val(item.Marks);
var newRow = $('<td></td>').append(input);
row.append(newRow);
So, now you have a reference to your input, and the code looks much cleaner.
At one point in the last 24 hours, I had a working function called get_contact_info which returned the contents of a series of text inputs.
Suddenly the code stopped returning the values and began returning "undefined" as the element values, though noting had been changed in the code or html.
custom.js contains the following
var first_name, last_name, email, phone_number;
var contact_info = [];
function get_contact_info(){
alert("This is the function called by the button");
}
/* contact_info[0] = document.getElementsByName('fname').value;
contact_info[1] = document.getElementsByName('lname').value;
contact_info[2] = document.getElementsByName('email').value;
contact_info[3] = document.getElementsByName('phone').value;
alert("Name = " + contact_info[0] + " " + contact_info[1]);
alert("Email = " + contact_info[2] + ", Phone Number " + contact_info[3]);
};*/
}());
My html is the following:
<form>
<table>
<tbody>
<tr><div class="custom text" style="color: red"><strong>Please enter your contact info to create a quote</strong></div></tr>
<tr><td></td></tr>
<tr>
<td><strong>First Name:</strong></td>
<td><input type="text" id="fname" value="Joe"/></td>
</tr>
<tr>
<td><strong>Last Name:</strong></td>
<td><input type="text" id="lname" value="Johnson"/></td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td><input type="text" id="email" value="joe#johnson.com"/></td>
</tr>
<tr>
<td><strong>Phone Number:</strong></td>
<td><input type="text" id="phone" size="15" value="555-1212"/></td>
</tr>
<tr>
<td><input id="contact_info" type="submit" value="Set My Contact Info" onClick="get_contact_info()" /></td>
</tr>
</tbody>
</table>
</form>
Am I implementing this incorretly?
I am attempting to teach myself basic javascript but I seem to be failing on this piece and don't see where.
Using Firebug in Firefox v30.0, a console call to
document.getElementsByName('fname').value;
returns "undefined"
document.getElementsByName('fname');
returns a NodeList, but no elements.
sigh
Use getelementbyidID not name, or set the name attribute.
contact_info[0] = document.getElementByID('fname').value;
You are using getElementsByName instead of getElementById which will not work given that you never provided any name attributes for the inputs
contact_info[0] = document.getElementById('fname').value;
contact_info[1] = document.getElementById('lname').value;
contact_info[2] = document.getElementById('email').value;
contact_info[3] = document.getElementById('phone').value;
The code you posted has syntax errors, and the part that seems to be throwing an error is commented out. As others have said, you have a problem with getElementsByName and getElementById. But your issues go further than that.
A form can be submitted without clicking the submit button, so it's usual to attach listeners that should run when the form is submitted to the form's submit handler. It also helps to pass a reference to the form using this (the reason will become clear later):
<form onsubmit="get_contact_info(this)" ...>
Form controls are only submitted if they have a name, giving them an ID is usually unnecessary, so change the IDs to names:
<td><input type="text" name="fname" value="Joe"></td>
And the submit button becomes:
<input type="submit" value="Set My Contact Info">
Now you also have a very convenient way to access the form controls using their name as properties of the form. Since a reference to the form was passed in the call (see above), the function can be:
var contact_info = [];
function get_contact_info(form) {
contact_info[0] = form.fname.value;
contact_info[1] = form.lname.value;
contact_info[2] = form.email.value;
contact_info[3] = form.phone.value;
alert("Name = " + contact_info[0] + " " + contact_info[1]);
alert("Email = " + contact_info[2] + ", Phone Number " + contact_info[3]);
}
Also note that getElementsByName returns a live NodeList that doesn't have a value property, so if you were going to use it, you'd use it like:
document.getElementsByName('email')[0].value
You could also create the array using an array literal:
contact_info = [form.fname.value, form.lname.value, form.email.value, form.phone.value];