How to get value of edit text with jquery - php

Hi i want to get changed text value from JQuery but i can't select edit text with JQUERY because edit texts generated from php while loop that this php code query on database and get value of edit texts and in my program i have edit button for every edit texts and when the user changed value of edit text i select new value and when user click edit button send this value from get method to another php page with jquery $.ajax function and send new value to that php code with ajax.But i don't know how can i select edit text that it's value changed because i don't know id of that edit text!.And when i set one id for every edit text i only get first edit text value from $("#id").change().val();.I use below code but it doesn't work.I am beginner in java script and don't know how fix this problem!.
var testAnswer;
function setNewTestAnswer(id){
testAnswer = $("#id").val();
}
function sendToEdit(pID,phID,thDate,type){
var info = 'pId='+pID+'&phId='+phID+'&testAnswer='+testAnswer+'&thDate='+thDate+'&type='+type;
}
2nd function use testAnswer that user changed in edit text.
php code
<?php
include 'Connect.php';
if(match($_POST['pId'], "/^[\d]+$/") ){
$pId = $_POST['pId'];
$result = mysql_query("select pName, pID, phName, phID, testHistoryDate, type, testAnswer from patient join reception using(pID) join physician using(phID) join testHistory using(rID) join test using(tID) where pID = $pId",$connection);
}
else
die("Insert true value");
while($row=mysql_fetch_array($result)){
echo "<tr><td>";
echo $row["pName"].'</td>';
echo '<td>'.$row["phName"].'</td>';
echo '<td>'.$row["testHistoryDate"].'</td>';
echo '<td>'.$row["type"].'</td>';
$type = $row['type'];
$testHistoryDate = $row['testHistoryDate'];
?>
<td>
<span id='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer' value='<?php echo $row['testAnswer']; ?>' />
</span>
</td>
<td>
<input type='submit' value='Edit' name='edit' id='edit' onclick="sendToEdit('<?php echo $row['pID'] ?>','<?php echo $row['phID'] ?>', '<?php echo $row['testHistoryDate'] ?>', '<?php echo $row['type'] ?>')" />
</td>
</tr>
<?php } ?>

tl;dr
So it isn't completely clear what you are trying to do here but I can explain a couple things that might help.
in html ids should be unique. You dont have to obey this rule for your page to work but you have found one of the consequences if breaking it: jQuery will only find the first one.
it is a good idea to base html ids on some unique attribute of your data eg the table row id.
You can get more creative with your jQuery selectors for example
$('input[type="text"]') // gets all the text inputs
Use classes. When you want to be able to easily select all of a group of html elements you should give them all the same class name. one element can have multiple class names and many elements can share a class name. you can then select them by class name using jquery like this:
$('.myclassname')
I think you need to change your php to look more like this:
<span class='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer-<?php echo $row['id'] ?>' value='<?php echo $row['testAnswer']; ?>' />
</span>

Since you're creating elements inside a php loop, you must be sure that every element has a unique id (or no id at all). You can use either an incrementing index, or some unique value in your array. At first glance, seems that $row['pID'] is a good candidate:
<input id='edit_<?php $row['pID'] ?>' type='submit' value='Edit' ... />
After that you should be able to target individual elements.

Related

How do I pass arguments from one php file to another?

I have to make an online shop.
I generate my products from a database like this:
$sql = "SELECT * FROM wblouses";
$result = mysql_query($sql);
if (! $result)
{
echo "eroare db database-item";
}
else
while($db_field = mysql_fetch_assoc($result)) {
echo "<div class=\"col-md-4\"><div class=\"thumbnail\"><form method=\"POST\" action=\"addToChart.php\" ><img style=\"display: block;\" src=";
echo $db_field["poza"]." height=\"250\" width=\" 400 \"> <p class=\"prices\">
<span class=\"price\" data-color=\"401\" >
<span class=\"currentPrice\"> ".$db_field["pret"]." LEI </span>
</span>
<input type=\"username\" name=\"username\">
<select id=\"myselect\" name=\"myselect\">
<option value=".$db_field["ID"].">SIZE</option>
<option value=\"XS\">XS</option>
<option value=\"S\">S</option>
<option value=\"M\">M</option>
<option value=\"L\">L</option>
</select>
<input type=\"submit\" value=\"add to chart\">
</p></form><button id=\"ilas\" onClick=\"fct(this.id)\">B3</button></div></div> ";
}
In another .php file I manage a database which represents a list of items selected from the one posted. How do I pass the id of a particular item to another file, I only seem to get the last generated id.
How can I pass some arguments to another php file?
The problem is that every product has it`s own generated div,dropdown and button with the same name and ID , how I find out in .php which product I refer to(it always refer to the last added product)?
#Skrrp
#TEster
Simple answer, you can't pass both bits of data from the same select.
You could do some funky concatenation, such as;
<option value=\"" . $db_field["ID"] . ";XS\">XS</option>
and then do a string spilt on the other side. This is silly. Don't do this.
If you have multiple products that you want the user to select from, what you want is 2 select drop-downs, one for product and one for size. If certain products are available only in certain sizes you will need some JavaScript to sort out the second.
What you are probably looking for is a hidden data field. It looks like you have already selected the product (and its ID) by the stage you generate this form. Rather than putting the $db_field["ID"] in the select, put it in its own control.
<input type=\"hidden\" name=\"id\" value=\"" . $db_field["ID"] . "\">
Then when you get to your next page, $_POST["id"] will contain the product ID you need.
As the above guys said,
I recommend using a hidden field to store the value.
$id = $db_field["ID"];
<input type='hidden' name='id' value='$id'>
Then just collect it using $_POST['id'] on the other php script.

jquery set value on button submittion

problem
i have two button "YES" and "NO". if user click YES then text input will appear with value set ex: value="$check['sum'];" but when user click No then text input will appear without value ex: value ="".
here is my code
<input id="test<?php echo $row['br_loc'];?>" value="<?php echo $value;?>" name="test" type="text" class="test" style="width:70px;display:none">
and jquery
$(document).ready(function(){
$("#Yes<?php echo $row['br_loc'];?>").click(function(){
$("#test<?php echo $row['br_loc'];?>").show(1000);
});
$("#No<?php echo $row['br_loc'];?>").click(function(){
$("#test<?php echo $row['br_loc'];?>").hide(1000);
});
thanks you
Try using the disabled attribute:
$("#test<?php echo $row['br_loc'];?>").attr('disabled','disabled');
and
$("#test<?php echo $row['br_loc'];?>").removeAttr('disabled');
Try this:
$(document).ready(function(){
$("#YES").click(function(){
$("#test").show(); //value of input as set before. so, just show
}
$("#NO").click(function(){
$("#test").attr('value','').show(); //set value = '' , and show
}
});
Use binding function so that you provide your JS code with exact parameters. Code like yours should never be used.
Object ID or class should contain alphanumerical characters only, should not begin with number(s), and optionally, - or _ might be used. Avoid spaces or, as you've already shown yourself, using embedded PHP code which is highly unlikely to work in any further project of yours. It's also dangerous.
instead of this code $("#Yes<?php echo $row['br_loc'];?>")
try the following
$("#test<?php echo $row['br_loc'];?>").
Because you used id of button as "test<?php echo $row['br_loc'];?>". so only your click event not worked.

How to make an inline editable content?

I have a list of products that I wish to be editable. When a user hits the edit button, then the content of only the selected product needs to be changed (for example to a textbox so the user can edit the title on the fly). But how do I prevent php to echo for example a textbox to all the products- I guess it would do that automatically?
I also guess that i should use some Jquery stuff to make the content editable :P ?
The list is being looped like this:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo $products['product_name'];
echo 'Edit me';
}
As your first commenter pointed out, PHP alone is not enough here. You'll need on-page JS code that can communicate the changes in the browser, and a PHP script that can take those changes and work them back into the database. You can either write that yourself, or use proven libraries that exist specifically for this purpose, like http://backbonejs.org/ or http://angularjs.org/
These are model/view frameworks that let you show a view of your database data on a page, while keeping them editable, updating the database records when you update the entry online. But be warned: if you've never worked with MVC frameworks, you get to look forward to probably being very confused at first. The approach is completely different from the much simpler "get data from db with PHP, generate page content, send off to client, the end" approach.
Not necessarily the most efficient, but if there aren't a huge number of products how about including a simple form for each product but just hiding it until the 'Edit' link is clicked?
The list/forms:
$items = $mysqli->query("SELECT product_name, product_id FROM products");
while($products = $items->fetch_assoc(){
echo "<span>" . $products['product_name'] . "</span>";
echo "<a class='editButton'>Edit</a>";
echo "<form action='products.php' method='post' style='display: none;'>
<input type='hidden' name='product' value='" . $products['prodcut_id'] . "' >
<input type='text' name='title' value='" . $products['product_name'] . "' >
<input type='submit' value='Update' >
</form>";
echo "<br/>";
}
The jQuery:
$(".editButton").click(function(){
//Hide the text entry and the edit link
$(this).prev().hide();
$(this).hide();
//Show the form
$(this).next().show();
});
If you'd rather not reload the page to submit changes you could submit them via ajax too for a more dynamic user experience.

pass the value inside php while loop to javascript using button onclick

I have a huge form and in part of the form I want to insert some value to database using js. I might not be clear about how to present the question but here my needs are:
suppose, I have two tables in database table1, table2. In a html form:
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1){ ?>
<option value"<?=$row['name']?>" name="option1"><?=$row['name']?></option>
<?php } ?>
</select>
<input type="file" name="file">
<input type="button" name="button" onclick="submit_form(true,'');">
Now, I want to pass the $row['name'] value to submit_form() function in javascript. The javascript code will check the value and return it to the form to submit it. My question is since the $row['name'] from table1 is inside the while loop, I cannot pass the value to javascript. If the form was small I could have done using submit button and check $_POST('submit') type. I want to insert the $row['name'] in this form to table2 as file name associated with the name.
As i understand you want to pass selected value from form to submit_form() function?
function submit_form(param1, param2){
var passedValue = document.getElementById('tab1').value;
// here is your old submit_form() function. passedValue contains
// your selected $row['name']
}
#Jhilke Dai, First of all your php code is little buggy, '=' sign must be in html not in php the correct code is
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1) { ?>
<option value="<? echo $row['name'] ?>" name="option1"><? echo $row['name'] ?></option>
<?php } ?>
</select>
<input type="file" name="file"> <input type="button" name="button" onclick="submit_form(true,'')">
You can use generic functions or even jQuery itenerations, to fetch form values
See the similar question answer : Get selected value/text from Select on change
function getDomValueByID( id ) {
return document.getElementById(id).value;
}
function submit_form( a, b ) {
var formValue = getDomValueByID( 'tab1' );
//OR
var jQueryFormValue = jQuery( "#tab1" ).val();
//Do what u want here.
}
In fact several consider it a very bad idea to pass the option data over via javaScript, if its already generated on page for the following reasons
Duplicate data, wasted bandwith.
Less portable code, non-OOP.
Harder to maintain, changes in your php code, requires changes in your javaScript code.
Also if you are really interested (this practice is sometimes frowned on). You can use the following as PHP code somewhere in the header. To pass PHP variables to JavaScript. However there are lots of better ways to do this, from JSONS to XML.
<?php optList = ['one', 'two', 'three']; ?>
<script type="text/javascript">
//Window represents the global variable space, and doing this is really bad practice as listed above.
window.optionList = [ <?php echo( implode(' , ', optList) );?> ];
</script>

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Categories