Input fields added dynamically through jquery not being submitted - javascript

I have made a table where if a user clicks on a td it converts into an input field with name and value.
The fields are created successfully but are not submitted along with the form.
In My HTML/PHP :
<tr>
<form action='form_handlers/assign_query.php' method='POST'>
<td >{$row['id']}</td>
<td class='editable-td' data-name='name'>{$row['name']}</td>
<td class='editable-td' data-name='phone_no'>{$row['phone_no']}</td>
<td class='editable-td' data-name='email'>{$row['email']}</td>
<td class='editable-td' data-name='type'>{$row['type']}</td>
<td class='short-cell editable-td textarea' data-name='query'>
<div class='scrollable'>{$row['query']}</div>
</td>
<td class='editable-td' data-name='agents'>{$row['agents']}</td>
<td class='editable-td'><button type='submit' class='cstm-btn' name='update_query'><i class='fa fa-pencil'></i></button></td>
</form>
</tr>
In my Js :
$('.editable-td').dblclick(function() {
if($(this).hasClass('enabled')) {
console.log('already enabled');
} else {
$(this).addClass('enabled');
if($(this).hasClass('textarea')) {
var text_content = $(this).find('.scrollable').html();
var name = $(this).data('name');
console.log(name);
$(this).html("<textarea name='"+name+"'>"+ text_content +"</textarea>");
}
else {
var text_content = $(this).html();
var name = $(this).data('name');
console.log(name);
$(this).html("<input type='text' name='"+name+"' value='"+ text_content +"' ></input>");
}
}
});
In form_hanlders/assign_query.php :
<?php
print_r($_POST);
?>
Input fields dynamically added by jQuery don't show up in $_POST array. But if I manually type in the exact same line that jQuery generates and paste it in the td, it gets submitted. Any help?
P.S : I have already read this , and this and this and they don't help.

The problem is because your HTML is invalid. You cannot have a form element as a child of a tr. If you check the HTML in the dev tools DOM inspector you'll see that the form element has either been moved outside of the table (so it no longer contains the input or textarea elements) or it has been removed completely.
To fix the problem the form needs to wrap the entire table, like this:
<form action="form_handlers/assign_query.php" method="POST">
<table>
<tbody>
<tr>
<td>{$row['id']}</td>
<td class="editable-td" data-name="name">{$row['name']}</td>
<!-- additional cells... -->
</tr>
</tbody>
</table>
</form>

Related

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

how to retrieve data from java listing using js

I want to get a data from listing and retrieve to popup.. when I use getElementById, it will only get a single id from another input. not from listing that i want.. so, I've come an idea to use array.. but I don't know how.. I'm using Java Play Framework
here is my code..
display.html
<script>
function openModifySchedule(staffId) {
if (!checkRequiredField()) {
alert("There Is Error(s) In The Form. Please Fix It Before Proceed.");
return;
}
var staffId = document.getElementById("staffId").value;
if (staffId == "") {
alert("Please Select Doctor Before Proceed");
return;
}
var url = "/DoctorSchedules/modifySchedulePopup?staffId=" + staffId;
mywindow = window.open(url,"mywindow","location=no,resizable=1,width=700,height=650,menubar=no,center=yes");
mywindow.moveTo(420,100);
}
</script>
<input type="hidden" id="staffId" name="staffDetails.staffId" value="${staffDetails?.staffId}">
<tbody>
#{list items:staffScheduleList , as:'stffSchedule'}
<tr id="list" align="center">
<td></td>
<td id="scheduleDate">${stffSchedule.scheduleDate}</td>
<td id="staffId"><a onClick="openModifySchedule()" href="#">${stffSchedule.staffId}</a></td>
<td id="staffName">${stffSchedule.staffName}</td>
<td id="deptName">${stffSchedule.deptName}</td>
<td></td>
<td></td>
<td></td>
<td id="contactNo">${stffSchedule.contactNo}</td>
</tr>
#{/list}
</tbody>
here is the function in controller..
display.java
public static void modifySchedulePopup(String staffId){
StaffDetails staffDetails = StaffDetails.find("byStaffId", staffId).first();
StaffSchedule staffSchedules = StaffSchedule.find("byStaffId", staffId).first();
renderTemplate("DoctorSchedules/doctorScheduleModifyPopup.html", staffDetails,staffSchedules);
}
hope someone can explain.
In the DOM, no two elements may have the same id attribute. Since all of the "td" elements in your table have id="staffId", getElementById() is free to return any one of them.
Since Play! comes with JQuery, you might was well use that instead of straight JavaScript (it's much easier). Briefly, you attach the same "click" event handler to all of the links and the click event handler knows which element was being clicked.
Here's simple snippet that demonstrates this:
<script>
$(function() {
$(".staff-id").click(function() { // attach the click event handler
var staffId = $(this).text();
alert(staffId); // open your new window here
});
});
</script>
#{list items:staffScheduleList, as:'stffSchedule'}
<tr id="list" align="center">
<td></td>
<td>${stffSchedule.scheduleDate}</td>
<td><a class="staff-id" href="#">${stffSchedule.staffId}</a></td>
<td>${stffSchedule.staffName}</td>
<td>${stffSchedule.deptName}</td>
<td></td>
<td></td>
<td></td>
<td id="contactNo">${stffSchedule.contactNo}</td>
</tr>
#{/list}

Get the selected rows from a table

I have a table that has 10 rows and 3 columns and each row has a checkbox associated with it. The user can select any number of rows and when he presses the Submit button an alert message needs to be displayed containing the values in all the selected rows preferably as a JSON string. How do I extract all the selected rows alone and convert it to a JSON string using either Javascript or Jquery?
I hope I've understood your requirements well. Please consider this solution.
$('#btn-table-rows').click(function (event) {
var values = [];
$('table #row-selector:checked').each(function () {
var rowValue = $(this).closest('tr').find('td.row-value').text();
values.push(rowValue)
});
var json = JSON.stringify(values);
alert(json);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>
<input id="row-selector" type="checkbox"/>
</td>
<td class="row-value">Row #1: Hello</td>
</tr>
<tr>
<td>
<input id="row-selector" type="checkbox"/>
</td>
<td class="row-value">Row #2: World</td>
</tr>
</table>
<button id="btn-table-rows">Process</button>

Find hidden input when inside a td tag that is near it in same row

I need to find a value of a hidden input in same table row but it seems that i cannot access it with how i am trying to.
function setDateTimeOn(elm) {
var formattedDate = GetCurrentDateTime(); //get formatted date
$(elm) //clicked button
.parent("td") // container td
.next() // next td
.find("span")
.text(formattedDate);
console.log(elm);
var hdn = $(this).closest('tr').find('input[type="hidden"]').val();
console.log(hdn);
}
http://jsfiddle.net/bthorn/xf12y7y4/
What I am searching for is this
<input type="hidden" name="GridView1:_ctl2:hndTxtId" id="GridView1__ctl2_hndTxtId" value="3601">
I want the value 3601 , it is in the same tr
HTML
<table>
<tr>
<td style="width:5px;">
<input type="hidden" name="GridView1:_ctl2:hndTxtId" id="GridView1__ctl2_hndTxtId" value="3601">
</td>
<td style="width:50px;"> <span id="GridView1__ctl2_lblVehicle0">413</span>
</td>
<td style="width:5px;">
<input type="button" id="GridView1__ctl2_AddButton0" name="GridView1:_ctl2:AddButton0" value="On" class="btn-blue" onclick="setDateTimeOn(this)">
</td>
<td style="width:150px;">
<span id="GridView1__ctl2_lblStormTimeOn"></span>
</td>
</tr>
I see it spit out the complete input element tag but the var hdn , I try to do a console.log(hdn) and it is undefined.
The problem is that you're using:
var hdn = $(this).closest('tr').find('input[type="hidden"]').val();
And this here is the global Window object. You want to use the element:
var hdn = $(elm).closest('tr').find('input[type="hidden"]').val();
Updated fiddle

Access textContent of hidden table cell

I'm working with an html form that displays rows of data only for data elements that are found with a submitted value in the database. For example, the following table row will be toggled off ( style="display:none" ) if there is no value found in the database for 'Seizures_Type', and WILL be displayed if there is a value found in the database.
The javascript works to concatenate values from several similar fields on the form and store in a single field, id="medalert".
When the script runs, it fails if it tries to access a field that is in the display:none state.
What would be a good way to allow the script to run fully, even if it encounters these hidden elements?
Build
<tr style="display:none">
<td title="seizures type">Seizures Type</td>
<td></td>
<td id="par_med_seizures_type"></td>
<td><input type="checkbox" id="chk_med_seizures_type"></td>
</tr>
<tr style="display:none">
<td title="seizures type">Seizures Medication</td>
<td></td>
<td id="par_med_seizures_medication"></td>
<td><input type="checkbox" id="chk_med_seizures_medication"></td>
</tr>
function buildMedAlert(){
var retval = "";
if (document.getElementById('par_med_seizures_type').textContent.length>0) {
retval += "Type: " + document.getElementById('par_med_seizures_type').textContent;
}
if (document.getElementById('par_med_seizures_medication').textContent.length>0) {
retval += "Medication: " + document.getElementById('par_med_seizures_medication').textContent;
}
document.getElementById('medalert').value=retval;
}
You should make a condition to check if the row is visible, give it an ID (since I don't believe you want to work on every element in the code) and then, make sure to check if the element is visible, like this:
var element = document.getElementById('element');
if(element.style.display != 'none'){
}
The thing is that you cannot access the contents of a hidden element since it is hidden and so, the javascript doesn't recognize it. You have to make sure the element is not hidden.
If I add the missing field medalert, it does not fail in neither Chrome nor IE10
function buildMedAlert() {
var retval = "";
if (document.getElementById('par_med_seizures_type').textContent.length > 0) {
retval += "Type: " + document.getElementById('par_med_seizures_type').textContent;
}
if (document.getElementById('par_med_seizures_medication').textContent.length > 0) {
retval += "Medication: " + document.getElementById('par_med_seizures_medication').textContent;
}
document.getElementById('medalert').value = retval;
}
Build
<table>
<tr style="display:none">
<td title="seizures type">Seizures Type</td>
<td></td>
<td id="par_med_seizures_type">Some type</td>
<td>
<input type="checkbox" id="chk_med_seizures_type">
</td>
</tr>
<tr style="display:none">
<td title="seizures type">Seizures Medication</td>
<td></td>
<td id="par_med_seizures_medication">Some med</td>
<td>
<input type="checkbox" id="chk_med_seizures_medication">
</td>
</tr>
</table>
<input type="text" id="medalert">

Categories

Resources