How to change input field back to text - javascript

I have a table and a script that makes each cell an input field when clicked on the edit button at the end of a row.
I submit the edited data via Ajax, but I want to make the input field back to normal text after I have edited it.
Here is the code:
//// EACH CELL INTO INPUT FIELD ////
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
var submit = "<input type='button' name='Submit' value='Submit' />";
tr.find(".button").html(submit);
});
});
//// END ////
//// ONCLICK SUBMIT SEND DATA VIA AJAX ////
$(".button input[type=button]").live('click', function() {
var data = $('form#muuda').serialize();
// post data using ajax
$.ajax({
type: "POST",
url: "index.php?leht=kast",
data: data,
success: function(data) {
alert("Andmed muudetud"); // show response from the php script.
}
});
});
//// END ////
HTML:
<form id="muuda" method="post" action="#">
<table>
<?PHP
$sql="SELECT * FROM nimed";
$result = mysql_query($sql)or die(mysql_error());
WHILE ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr class="row">';
echo '<td class="td" title="id">'.$row["id"].'</td>';
echo '<td class="td" title="eesnimi">'.$row["eesnimi"].'</td>';
echo '<td class="td" title="perenimi">'.$row["perenimi"].'</td>';
echo '<td class="button" title="button"><button class="edit">Edit</button></td>';
echo '</tr>';
}
?>
</table>
</form>
Here is a picture of the preview:
https://lh6.googleusercontent.com/-vVnabdBzFlA/UBjTRhifpWI/AAAAAAAACAo/RvAgpi7x2ik/s488/Ajax%2520submit.jpg

You can just reverse the process you use to turn it from text to an input box:
tr.find('.td').each(function () {
var value = $(this).find('input').val();
$(this).html(value);
});
You will have to set the variable tr to the right row, of course.

Related

How can I get my information to display into a link <a href> or a <div>?

The issue I am having is that I need the search results to be displayed in a link or a . Right now they display into a text input field. When I try to change it to a link or div no text is generated. I am almost certain it has to do with the java/jquery script I have. The script I am using is an open source script that I need for simple reasons.
What I have tried is changing the element in which the script calls for from an input to a div or a href. I have googled and tried to find some sort of reference to which the script selects what elements to display the code into and the only thing I can identify as being the problem is, "userid = ui.item.value; // selected id to input".
index.php - Script
<script type="text/javascript">
$(document).ready(function(){
$(document).on('keydown', '.username', function() {
var id = this.id;
var splitid = id.split('_');
var index = splitid[1];
$( '#'+id ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,request:1
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // display the selected text
var userid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {userid:userid,request:2},
dataType: 'json',
success:function(response){
var len = response.length;
if(len > 0){
var name = response[0]['name'];
var displayid = response[0]['displayid'];
document.getElementById('name_'+index).value = name;
document.getElementById('displayid_'+index).value = displayid;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function(){
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='username' id='username_"+index+"' placeholder='Enter username'></td><td><input type='text' class='name' id='name_"+index+"' ></td><td><input type='text' class='displayid' id='displayid_"+index+"' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
</script>
index.php - Html
<div class="container">
<table border='1' style='border-collapse: collapse;'>
<thead>
<tr>
<th>Search</th>
<th>Name</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<tr class='tr_input'>
<td><input type='text' class='username' id='username_1' placeholder='Enter username'></td>
<td><input type='text' class='name' id='name_1' readonly></td>
<td><input type='text' class='displayid' id='displayid_1' readonly></td>
</tr>
</tbody>
</table>
<br>
<input type='button' value='Add more' id='addmore'>
</div>
getDetails.php
$request = $_POST['request']; // request
// Get username list
if($request == 1){
$search = $_POST['search'];
$query = "SELECT * FROM item_template WHERE name like'%".$search."%'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
$response[] = array("value"=>$row['entry'],"label"=>$row['name']);
}
// encoding array to json format
echo json_encode($response);
exit;
}
// Get details
if($request == 2){
$userid = $_POST['userid'];
$sql = "SELECT * FROM item_template WHERE entry=".$userid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['entry'];
$name = $row['name'];
$displayid = $row['displayid'];
$users_arr[] = array("entry" => $userid, "name" => $name,"displayid" => $displayid);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
}
I except the selector is wrong in the script, where it selects where to copy the text to.
You just need to use innerHTML instead of value.
document.getElementById('name_'+index).innerHTML = name;
document.getElementById('displayid_'+index).innerHTML = displayid;
and change the input tag to div tag. You might want to read more about innerHTML.

POST submit to mysql using php the value from append javascript

I'm trying to POST submit the data to mysql using php from append javascript.
Here's the modal where data come from append which is in php.
<tr onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' class='productuse' id='productuse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' class='description' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='msrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;'><textarea rows='4' cols='10' name='cost' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td></tr>";
}
?>
</tbody>
Here's the append js from modal to table.
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
var value5 = (getRow.find('td:eq(0)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea value="'+ value +'</textarea></td><td class="item-name"><textarea class="check" name="check[]" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea value= "' + value2 +' </textarea></td><td class="item-name"><textarea value= "' + value3 + ' </textarea> </td><td><textarea name="Msrp" value="' + value4 + '</textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty[]"> </textarea></td><td class="item-name"><textarea id="price" class="price" name="price[]" disabled></textarea></td></tr>');
}));
});
});
Questions is. how can i POST submit to mysql using PHP PDO the value come from append javascript??
You'll need to put any input data inside of a form, then create a PHP script that handles the POST request and INSERTS the data into your MySQL database.
Your form tag should look something like this:
<form class="post-form" action="script_that_handles_post.php" method="post">
So, you'll want to use $_POST['']. For example, the name in your first table row is name="check", you'll use $_POST['name'] to get the value of that field. Do that for each field that you want to store. Preferably, you should store each of those in their own variables or an array.
Then, for your AJAX you'll have to include the library somehow. If you aren't already, put this in your footer below the jquery source:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
Now you can add your AJAX POST request. Here's some code that should do it:
$(".post-form").submit(function (event) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url:$form.attr('action'),
type:'POST',
data: serializedData
});
request.fail(function (jqXHR, errorThrown){
console.error(
"Error: " + errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
What this code is doing is taking the action path of your form and posting the data from the inputs of the fields there.
I hope this helps.

Id not getting in input text field using dropdown javascript

I am using javascript for getting dropdown select id id='odrid',
here is the script:
$('#odrid').change(function(){
$.getJSON(
'fetch.php',
'odrid='+$('#odrid').val(),
function(result){
$('#item').empty();
$.each(result, function(){
$('#item').val(this['item']);
});
}
);
});
This drop down script runs in another script for adding dynamic form field:
<script>
$('#odrid').change(function(){
$.getJSON(
'fetch.php',
'odrid='+$('#odrid').val(),
function(result){
$('#item').empty();
$.each(result, function(){
$('#item').val(this['item']);
});
}
);
});
$(function() {
// register listener
$('.form-control1').on("change.add", calculateSum);
// initial calculation
calculateSum();
// button for adding new row
$(".addmore").click(function() {
$('.form-control1').off("change.add");
//addRow();
var count = $('#counter').val();
$("<tr>" +
"<td><input type='checkbox' class='case'/></td>" +
"<td><select id='odrid'><?php
$query = mysql_query('select * from cart_sample');
while($row = mysql_fetch_assoc($query)) {
echo '<option value='.$row['odrid'].'>'.$row['odrid']. '</option>';
}
?></select></td>" +
"<td ><input id='item' type='text' name='txt_quantity[]' value='' /></td>" +
"</tr>").insertAfter("tr:last-child");
count++;
$('#counter').val(count);
$('.form-control1').on("change.add", calculateSum);
calculateSum();
});
</script>
this is my front end:
The problem is that I didn't get the value of #item in my output.
How can I fix this issue? does anyone know the problem in my code?
Thanks in advance!
i think the problem is with your id
you are using $("#item") in your jquery and you have defined items as your id
<input id='items' type='text' name='txt_quantity[]' value='' />
change it to item
<input id='item' type='text' name='txt_quantity[]' value='' />
or change
$("#items") in jquery
and it should work as expected

how to check checkbox in javascript loop

I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>

My Jquery code still won't work , yet nothing is shown in firebug

I posted this code minutes 15 mins ago and I did get help for the preventDefault issue , but now I'm not getting my alerts to work , yet firebug doesn't show any error related to this code .. May i ask where I'm going wrong ,
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.preventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.preventDefault();
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
I suggest changing your design. Using <form> codes and posting isn't always the best way of sending your data to another (or the same) page for PHP processing. Instead, switch over to using AJAX code to submit your form.
For one thing, this will allow you to get away from the e.preventDefault kludges. A number of things will iron themselves out if you use the AJAX approach (instead of submitting a form). I can see that you're already using AJAX in your code, but if you're still uncomfortable with it you can check out these other answers:
Form not posting correctly
Place PHP results inside HTML Page
Update data in a DIV
Change your #edit_fields_submit input field from type="submit" to type="button" and use javascript/AJAX to:
Get all the values you would normally submit as a <form>;
Use AJAX to submit them to a PHP file for processing
In the success: function of the AJAX code block, use javascript to send the user over to whatever page you want them to see next
Example:
$('#edit_fields_submit').click(function(event) {
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
var field_data = //you know how to get these values
var project_id = //etc
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/myprocessor.php",
dataType: "json",
data: string,
success: function(data){
document.location.href='yournewpage.php';
}
});
});

Categories

Resources