Using information I found in this question I have been able to retrieve my driver information, and combining it with rowIndex place it in the correct cell.
reservations.rows[whichRow].cells[7].innerHTML = which_driver;
reservations.rows[whichRow].cells[7].textContent = which_driver;
I've tried both and the proper data shows.
Now using information I found in another question (I can't find it) I have been using this function to retrieve the values as I loop through the selected rows (checkbox)
<script type="text/javascript">
$(function()
{
$('#submitButton').click(function(){
var values = $("#main_table table input[name=name]:checked").map(function() {
row = $(this).closest("tr");
return {
recordid : $(row).find('input[name=record_id]').val(),
firstname : $(row).find('input[name=firstname]').val(),
lastname : $(row).find('input[name=lastname]').val(),
timeneeded : $(row).find('input[name=timeneeded]').val(),
dateneeded : $(row).find('input[name=dateneeded]').val(),
pickup : $(row).find('input[name=pickup]').val(),
dropoff : $(row).find('input[name=dropoff]').val(),
drivername : $(row).find('textContent[name=driver_name]').val()
}
}).get();
console.log(values);
});
});
When I view the objects in the console all the other fields show the correct, but driver name is 'undefined'.
Is there a way to grab that information or a way to put the data from the popup into the "value" of the proper cell. So far, I haven't been able to get that data to show.
Thank you
Here's the actual from the HTML -
"<td id="driverlist" width='125' align='left' onClick="selectValue('id',this)" value="?" > <input type="text" id="driver_name" name='driver_name' "size='15' style='font-weight: 700' value=''"> </td>"
When the user clicks in the field it fires a function that returns the rowIndex and then fires the Popup, once a person is selected then it returns the value and fills in the proper cell –
I modified the map function to read
drivername : $(row).find('textContent[name=driver_name]').text()
and now it at least returns "" and not undefined. –
The solution was to use
: $(row).find('td:eq(7)').text()
Related
I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?
I have a php table created by a mysqli query where I want users to be able to update the date values of a text cell. For other formatting reasons, I have chosen not to use the date input.
My script works for other forms with an id that does not include brackets and changes the form value immediately and correctly. However, when I apply the onchange function to the table cell, it seems the brackets in the id may be holding me up. I can see in the console that I am calling the correct bracketed id, however, nothing else happens.
Here is my cell:
<td>
<input type='text' class='form-control form-control-sm'
id='tbl_date01[".$tbl_ID."]' name='tbl_date01[".$tbl_ID."]'
value='".$tbl_date01."' onchange=\"dateChange()\" required />
</td>
Here is my script:
function dateChange(){
var id = (event.target.id);
var y = document.getElementById(id).value;
if(y === '?'){
$("#"+id).val(new Date().toJSON().slice(0,10).substring(5,7) + '/' + new Date().toJSON().slice(0,10).substring(8,10) + '/' + new Date().toJSON().slice(0,10).substring(0,4));
return;
};
};
I have a bit of HTML here:
<tr taskId="(#=obj.task.id#)" assigId="(#=obj.assig.id#)" class="assigEditRow" >
<td><select name="resourceId" class="get-resources formElements"></select></td>
<td><span class="resources-units"></span></td>
<td><span class="resources-quantity"></span></td>
<td><input type="text" placeholder="Required Q"></td>
<td align="center"><span class="teamworkIcon delAssig" style="cursor: pointer">d</span></td>
</tr>
And a bit of JS here:
'use strict';
function addResourceFunction(){
let ResourcesJSON = (json) => {
let Resources = json;
console.log(Resources);
let contactsLength = json.length;
let arrayCounter = -1;
let resID;
let resName;
let resUnit;
let resQuantity;
let Option = $('<option />');
let assignedID = $('tr.assigEditRow:last').attr("assigId");
while(arrayCounter <= contactsLength) {
arrayCounter++;
resID = Resources[arrayCounter].ID;
resName = Resources[arrayCounter].name;
resUnit = Resources[arrayCounter].unit;
resQuantity = Resources[arrayCounter].quantity;
$('.assigEditRow').last().find('select').append($('<option>', {
value: resName.toString(),
text: resName.toString(),
resourceID: resID.toString(),
resourceUnit: resUnit.toString(),
resourceQuantity: resQuantity.toString()
}));
}
}
$.getJSON("MY JSON URL IS HERE", function(json) {
ResourcesJSON(json);
});
};
So what's actually going on here: I get my data from the URL (JSON array), trigger the addResourceFunction() on click to create a new table row and to add a new select with options passed from the array. As you see from my HTML markup, the select input is placed in td.get-resources, and all that works good. I get my date set, I populate the select field and all works good. I can add as many rows/select dropdowns as I want.
Also, every option has a few custom attributes (you can see it in my JS code above), and I want to add the values of those attributes to the second and third column of the row (in HTML those are span.resources-units and span.resources-quantity). The thing is, I have no clue how to make it work 1:1, meaning that one select dropdown "alters" only units and quantity of its own row. Below is the code for that:
let idCounter = 1;
$(document).on('change', '.get-resources', function() {
$('.assigEditRow').last().find('.resources-units').attr('id', 'units-' + idCounter);
$('.assigEditRow').last().find('.resources-quantity').attr('id', 'quantity-' + idCounter);
this.resourceUn = $( ".get-resources option:selected" ).attr( "resourceUnit" );
this.resourceQuant = $( ".get-resources option:selected" ).attr( "resourceQuantity" );
$('#units-' + idCounter).append(this.resourceUn);
$('#quantity-' + idCounter).append(this.resourceQuant);
idCounter++;
});
What happens is that if I add one select input, and change options, the thing works. When I add another one and change its options, it gets attributes of the first one. Adding more - same thing. Whatever I change, it takes the attribute value of the first item added.
Try getting the id from the element instead of from the variable, since you always update the element with the id of the counter, instead of the element with the id of the row that was clicked.
Hmm, what does the counter do exactly? The more I look at it, the less I understand. What I do know is that you're not selecting the correct elements by using the idCounter to reference the correct row.
You want to do something like
$(document).on('change', '.get-resources', function() {
//var row = this;
this.find(/* Some path to the second column */).att(/* some att to change */);
this.find(/* Some path to the third column */).att(/* some att to change */);
});
where you always use the row as the root again, instead of finding a certain id, so you only update that row.
Native:
<table>
<tr>
<td>
<select>
<option data-text="resName1" data-resourceID="resID1" data-resourceUnit="resUnit1" data-resourceQuantity="resQuantity1">1</option>
<option data-text="resName2" data-resourceID="resID2" data-resourceUnit="resUnit2" data-resourceQuantity="resQuantity2">2</option>
<option data-text="resName3" data-resourceID="resID3" data-resourceUnit="resUnit3" data-resourceQuantity="resQuantity3">3</option>
</select>
</td>
<td>
<div class="column2"></div>
</td>
<td>
<div class="column3"></div>
</td>
</tr>
</table>
<script>
document.addEventListener('change', function ( event ) {
var select = event.target,
option = select.options[select.selectedIndex],
values = {
'text' : option.getAttribute('data-text'),
'resourceID' : option.getAttribute('data-resourceID'),
'resourceUnit' : option.getAttribute('data-resourceUnit'),
'resourceQuantity' : option.getAttribute('data-resourceQuantity')
},
row = select.parentNode.parentNode,/* depending on how deep the select is nested into the tr element */
column2 = row.querySelector('.column2'),
column3 = row.querySelector('.column3');
column2.textContent = 'some string with the values you want';
column3.textContent = 'some string with the other values you want';
});
</script>
Basically you start with the select that was changed, from there you get the option node that was clicked. Then you get the attributes you need from that option. Then you go up a few nodes to the row parent and find the two columns inside that row. Then you can set the content of these two columns.
So I have a dynamic form that has two columns. One has a job name and the other has an input box where the user could enter their on description of the job.
while($install_table_r = tep_db_fetch_array($install_table_query))
{
echo'
<tr class="dataTableRow">
<td class="dataTableContent">
<input type="text" id="job_name" name="job_name"
value="'.$install_table_r['name_of_job'].'" disabled />
</td>
<td class="dataTableContent">
<input type="text" name="job_desc" value="'.$install_comment['comment'].'"
onChange="insertCommentInstall(this.value,)" />
</td>
</tr>
';
}
So as you can see I have a while loop that populates this form. So it could potentially have a lot of input boxes that you can use to describe the jobs.
The issue I am having is that, when I handle this form with the AJAX I have set up. The javascript simply grabs the last job on the list and uses that as it's jobs name. So in essence it is grabbing the input box correctly it's just placing it in the wrong row.
Here is the javascript that handles this change.
var job = document.getElementsByNames("job_name").value;
var comment = document.getElementsByNames("job_desc").value;
var url = "<?php echo FILENAME_ORDERS_EDIT_AJAX; ?>?action=insert_comment_install&oID=<?php
echo $_GET['oID']; ?> &new_comment=" + value + "&jobname=" + job;
I know I should be grabbing the elements with getElementByNames but I just don't know how to pair up the comment with the proper job that it's supposed to go with. So if someone comments next to the input box for Granite Job the comment should be paired up with the job name 'Granite Job' in the database. Instead currently it will just be paired up with the last job on the list which is 'Cabinet Assembly'.
Any help would be appreciated.
First of all, you have a HTML error for the attribute id
You may not in HTML standards to give a same value for id attribute to a multiple elements.
But fortunately we can use this unique identifier to make your code works
You can edit your PHP code to some thing like this:
$counter=0;
while($install_table_r = tep_db_fetch_array($install_table_query))
{
echo'
<tr class="dataTableRow">
<td class="dataTableContent">
<input type="text" id="job_name_'.$counter.'"
value="'.$install_table_r['name_of_job'].'" disabled />
</td>
<td class="dataTableContent">
<input type="text" id="job_desc_'.$counter.'" value="'.$install_comment['comment'].'"
onChange="insertCommentInstall(this.value,'.$counter.')" />
</td>
</tr>
';
$counter++;
}
You can see we added a counter to identify our rows
Updating your Javascript code will be as follow:
var insertCommentInstall=function(value,identifier){
var job = document.getElementById("job_name_"+identifier).value;
var comment = document.getElementById("job_desc_"+identifier).value;
var url = "<?php echo FILENAME_ORDERS_EDIT_AJAX; ?>?action=insert_comment_install&oID=<?php echo $_GET['oID']; ?> &new_comment=" + value + "&jobname=" + job;
}
When you use a selector like getElementsByClassName or getElementsByTagName you are retrieving a nodelist of all elements with the specified attribute (adding a classname to your inputs would make this easier). You need to specify one particular node out of the nodelist in order to fetch it's value. In order to retrieve all values in your nodelist you need to loop through it and push the values of all its nodes into an array.
//finds all elements with classname "jobs"
var jobs = document.getElementsByClassName("jobs");
//create new array that we push all the values into
var jobValues = [];
//loop through our jobs nodelist and get the value of each input
for (var i = 0; i < jobs.length - 1; i++) {
jobValues.push(jobs[i].value);
}
jobValues; //gives you a list of all the values you pushed into the array
jobValues[5]; //gives you the value of the 6th input you looped through
in my form, the user can click a button to create input fields. Inside each of the created input fields, they can click the "add media links" button to create another input field underneath. They can add as many media links as they please or none at all. The first set of input fields are also sortable. I have the user interface working, I'm just wondering how to go about processing it.
right now, I am basically grabbing all of the values entered from the first set of input fields (aka "thestepvalues" in the code) and then grabbing all of the values entered from the second set of input values (aka "links" in the code) and then URL enconding it and serializing it to send to the my process.php file. The code is below:
$("#new_post").submit(function(e){
e.preventDefault();
//enter each of the values for 'the step' input field into an array
var thestepvalues = $("input[name='thestep\\[\\]']")
.map(function(){return $(this).val();}).get();
//enter each of the values for each 'links' input field into an array
var linkvalues = $("input[name='link\\[\\]']")
.map(function(){return $(this).val();}).get();
//this will basically convert everything entered into the steps as well as the links fields
//into URL appropriate strings to pass on to the process.php file
var i, string="";
for(i=0;i<thestepvalues.length; i++){
string += "thesteps[]=" + encodeURI(thestepvalues[i]) + "&";
}
for(i=0;i<linkvalues.length; i++){
string += "links[]=" + encodeURI(linkvalues[i]) + "&";
}
//send the data from the string (both kinds of input fields) as well as any
//other input fields (that aren't dynamic) from the form
$.post("process.php", string + $("#new_post").serialize(),
function(data){
if(data.email_check == 'invalid'){
$("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}, "json");
});
For a sample of data entered into the form, how do I go about indicating which link belongs to the parent input field? Baring in mind the parent input fields are sortable jquery ui elements.
here's a sample set of data entered, as you can tell I have no way of knowing which input field the child links belong to:
[thesteps] => Array
(
[0] => This is really the second input field, but dragged up to the first position.
[1] => This is the second input field, but used to be in the first position.
[2] => this is the third input field
)
[links] => Array
(
[0] => this is the first (child) link for the first position.
[1] => this is actually the (child) link for the third field!
)
Any help would be greatly appreciated, thanks in advance
-- 24x7
You could use HTML5 custom data attributes, setting the value of each linked set to be the same number.
For example:
<input id="1" data-newinput-id="1" />
<input id="2" data-newinput-id="1" />
<input id="3" data-newinput-id="2" />
<input id="4" data-newinput-id="2" />
Even if the inputs are re-arranged, you can match them up by getting the attribute values in jQuery like so:
var id = $(this).attr("data-newinput-id"); // 1