Getting Value of Input Element Created After DOM Load - javascript

I have multiple input elements arranged in 16 rows and 5 columns (Just like a grid) . The contents of the 16 rows are inserted into a mysql table as 16 records with each record contains 5 fields. I want a method to get the value of all the input into an array using jquery and pass this to a ajax post request.
dataentry.php contains this code
jQuery('#metentry').submit(function(e){
e.preventDefault();
// getting data from form to variables
var date=jQuery('#stddate').val();
var kgsunit=jQuery('#unit').val();
var kgsshift=jQuery('#shift').val();
//sending data to script
jQuery.post("get_blank_form.php", {
"date":date,
'unit':kgsunit,
'shift':kgsshift,
}, function(data) {
//displaying message
jQuery('#blankform').html(data);
jQuery('#formpanel').hide();
});
get_blank_form.php contains this code:
echo'<form id="shiftentry" name="shiftentry" >';
echo "Date:<input id=shiftdate value='".$date."'/>";
echo "Unit:<input id=shiftdate value='".$unit."'/>";
echo "Shift:<input id=shiftdate value='".$shift."'/><br/>";
echo "<table><tr><th>No</th><th>Ele</th><th>Location</th><th>Drate </th><th>H3 Val </th><th>Part </th> <th>Iod</th><th>Cont. </th></tr>";
while($row2=mysql_fetch_array($result_sec))
{
echo "<tr>";
echo "<td>".++$rc."</td>";
echo "<td><input size='5' id='".$row2['ele']."' value='".$row2['ele']."' /></td>";
echo "<td><input id='".$row2['loc_id']."' value='".$row2['loc']."' /></td>";
echo "<td><input size='5' id='drate".$rc."' value='".$row2['drate']."'/></td>";
echo "<td><input size='5' id='h3".$rc."' value='0' /></td>";
echo "<td><input size='5' id='part".$rc."' value='0' /></td>";
echo "<td><input size='5' id='iod".$rc."' value='0' /></td>";
echo "<td><input size='5' id='cont".$rc."' value='0' /></td>";
echo "</tr>";
}
echo " </table>";
echo '<div align="center">';
echo '<input type="submit" id="submit2" name="submit2" value="Submit" width="30" />';
echo '</div>';
echo '</form>';
Both the above scripts are working and this will add a form"shiftentry" to the DOM in dataentry.php. This form conains around 21 rows and 8 columns containing input elements. I want a method to get the values in this 21 x 8 input elements and pass it to a jQuery post request. Since the form is added after the DOM is loaded, how to get the value?
My final aim is to append this 21 rows into a mysql table. This part I knew, once I get all the values. Any suggestions ?
I have this function which create a multi dimensional array of input values. But in this casethe 'form1' is loaded before DOM is completed. But in the above scenario, form is dynamically added after DOM loding is completed
jQuery('#form1').submit(function(e){
e.preventDefault();
var arr = jQuery('#form1 tr:gt(0)').map(function() {
return [jQuery('input', this).map(function() {
return this.value;
}).get()];
}).get();
});
I also have another jquery script in this page which is used to traverse through the input boxes (obviously, these input boxes are loaded after DOM)
jQuery(document).delegate('input','keyup',function(e){
if(e.which==39)
jQuery(this).closest('td').next().find('input').focus();
else if(e.which==37)
jQuery(this).closest('td').prev().find('input').focus();
else if(e.which==40)
jQuery(this).closest('tr').next().find('td:eq('+jQuery(this).closest('td').index()+')').find('input').focus();
else if(e.which==38)
jQuery(this).closest('tr').prev().find('td:eq('+jQuery(this).closest('td').index()+')').find('input').focus();
});
How can I use the delegate option in the script used for traverse in the script for getting input values?

Related

Passing a var in the same php page without refresh

I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});

Getting text and sending it to a php function using javascript

I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>

Copy input text to another, inside a foreach loop?

This page generates a table contaning routes, and in the end of every "tr" there is a button that should copy the text inside those 2 fields in each line to the Name3 and Name 4 inputs, respectively.
But when I click, nothing is happening, I think that getElementById("Name1_".index) is making the hole code invalid, but how to make it correctly?
<script type="text/javascript">
function copyTextValue(key) {
var index = key;
var text1 = document.getElementById("Name1_".index).value;
var text2 = document.getElementById("Name2_".index).value;
document.getElementById("Name3").value = text1;
document.getElementById("Name4").value = text2;
}
</script>
<input type="text" id='Name3' />
<input type="text" id='Name4' />
<?php
$get_rotas = file_get_contents('routes.txt');
$array = explode("\r\n", $get_rotas);
foreach($array as $key=>$rota) {
//Route(rota) Example: TRM J169 BLH V16 BXK|3666
$rota_distance = explode("|", $rota);
echo "<tr bordercolor='#FFFFFF'>";
echo "<td><input type=\"text\" id=\"Name1_$key\" value='" . $rota_distance[0] . "'/></td>";
echo "<td><input type=\"text\" id=\"Name2_$key\" value='" . $rota_distance[1] . "'/></td>";
echo "<td><input type=\"button\" onclick=\"copyTextValue($key);\" value=\"Copy\" ></td>";
echo "</tr>";
}
?>
For concatenating strings in JavaScript use + instead of ..

How to return mysql data to webpage without refresh (ajax/jquery/php/mysql)

I managed to get quite far with another question last night but then I read that mysql_ was deprecated I switched to mysqli. Anyway I have the following php within my search.php file -ve kept some comments in which worked under my last attempt.
// Get all records
while ( $row = $results->fetch_assoc())
{
//$data[] = $row;
echo ('COLUMN1:'.$row["COLUMN1"]);
echo ('COLUMN2:'.$row["COLUMN2"]);
echo ('COLUMN3:'.$row["COLUMN3"]);
echo ('<br>');
}
$mysqli->close();
//echo json_encode( $data );
?>
And I want to display this data within a result div on my index.html page. I will eventually want to replace this data with a graph but one step at a time. I am struggling to understand how the data is passed between Ajax and php. This is my jquery/ajax:
$('#btn_search').click(function(){
txt_search = $('#txt_search').val();
$.ajax({
url: './php/search.php', //the script to call to get data
data: {search: txt_search}, //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
$('#result').append(rows);
}
}); return false;
});
I want to be able to write any columns from the DB table into the div, displaying as many rows as possible. I was originally using the following which wasn't quite working (only displaying 2 rows..I can see why (poor understanding of arrays I think):
/*for (var row in rows)
{
var COLUMN1 = rows[1];
var COLUMN2 = rows[2];
$('#result').append("<b>COLUMN1 </b>"+COLUMN1 e+"<b> COLUMN2: </b>"+COLUMN2).append("<hr />");
} */
EDIT: HTML
<div id="main">
<form id="search_form" role="form" action="" method="post">
<div class="form-group">
<input type="text" class="form-control" name="txt_search" id="txt_search" placeholder="Enter name here" autocomplete="off" >
<p></p>
<button type="submit" id="btn_search" class="btn btn-default">Retrieve </button>
</div>
</form>
<div class="result" id="result">this accessed by jquery and will be replaced</div>
/div>
Anyway I have a div called result which I would like to populate with a table of results just now. Can anyone answer and help me get a better understanding (I am finding a problem with this type of thing is there are hundreds of examples online, no explanation of why they doing what they are doing and all of them are different).
EDIT 2: Removed, Edit 3 contains better code:
EDIT 3: HTML into a variable:
$HTML = "<table border='1' >";
$HTML .= "<tr>";
$HTML .= "<td align=center> <b>Column1</b></td>";
$HTML .= "<td align=center><b>Column2</b></td>";
$HTML .= "<td align=center><b>Column3</b></td>";
// Get all records
while ( $row = $results->fetch_assoc())
{
$HTML .= '<tr>';
$HTML .= '<td align=center>'.$row["COLUMN1"].'</td>';
$HTML .= '<td align=center>'.$row["COLUMN2"].'</td>';
$HTML .= '<td align=center>'.$row["COLUMN3"].'</td>';
$HTML .= '</tr>';
}
$mysqli->close();
$HTML .= "</table>";
echo $HTML;
echo json_encode( $HTML );
?>
In this specific example just to demonstrate you can change the content of #result div by just using this in your success function:
$('#result').html(rows);
But normally you would create a some HTML structure in your search.php file and generate some HTML dynamically and then replace target #result div with that of returned by search.php.
Also you need to change the file extension of index.html to index.php
Edit: The cause is to remove datatype: json.

Dynamic way to get a list of ticked checkboxes on a php generated page

I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});​
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!

Categories

Resources