javascript to retrive value from html - javascript

I'm new to javascript. Now i want to get value from html tag (value get from database). If there is only one record that fetch from database, my code is work. But if there is more than one record, there is not work, only first record that work.
Here is code
*PHP*
$sql = mysql_query("SELECT * FROM users"); //suppose, there are 5 records
while($row = mysql_fetch_array($sql)){
//fetch value from db
$u_name = $row['U_Name'];
$u_gender = $row['Gender'];
$u_email = $row['Email'];
echo "<div class='loop'>";
echo "<p><input type='radio' name='user' value='1' />Name</p>
<p><input type='radio' name='user' value='2' />Gender</p>
<p><input type='radio' name='user' value='3' />Email</p>";
//user info
echo "<div class='user_info'>";
echo "<input type='hidden' class='u_name' value='$u_name' />";
echo "<input type='hidden' class='u_gender' value='$u_gender' />";
echo "<input type='hidden' class='u_email' value='$u_email' />";
echo "</div>";
//button
echo "<div class='user_button'>";
echo "<a style="text-decoration: none; color: #000000;"
class="button_action" id="button_action" href="#"
onclick="return false;">Info</a>";
echo "</div>";
//save final result
echo "<input type='hidden' id='final_name' value='' />";
echo "<input type='hidden' id='final_gender' value='' />";
echo "<input type='hidden' id='final_email' value='' />";
echo "</div>";
}
When user choose which radio button, and click on Info button, it will alert the the info of user.
if user choose radio Name and click button Info --> alert name of user
if user choose radio Gender and click button Info --> alert gender of user
if user choose radio Email and click button Info --> alert email of user
Once, user choose or change radio button, i will transfer the value of user to the point save final result (in my php code).
Javascript (when user change radio button)
$('input[name=user]').bind('change', function(){
var n = $(this).val();
switch(n){
case '1':
var name = $(this).parents('.loop').find("u_name").val();
document.getElementById("final_name").value = name;
break;
case '2':
var gender = $(this).parents('.loop').find("u_gender").val();
document.getElementById("final_gender").value = gender;
break;
case '3':
var email = $(this).parents('.loop').find("u_email").val();
document.getElementById("final_email").value = email;
break;
}
});
Here is action when user click on button Info now, i alert only name
$(".button_action").bind('click', function(){
var u_name = $(this).parents('.loop').find("#final_name").val();
var u_gender = $(this).parents('.loop').find("#final_gender").val();
var u_email = $(this).parents('.loop').find("#final_email").val();
alert(u_name);
});
This code correct only first record that fetch from database. Other records, it cannot get the value. Can you help to modify or change my code to the correct one?
Thank in advance.

It is because you are using duplicate id values, ID of an element must be unique. In this case you need to use name for the hidden elements instead of ID
echo "<input type='hidden' name='final_name' value='' />";
echo "<input type='hidden' name='final_gender' value='' />";
echo "<input type='hidden' name='final_email' value='' />";
then
$('input[name=user]').bind('change', function () {
var n = $(this).val(),
$loop = $(this).closest('.loop');
switch (n) {
case '1':
var name = $loop.find('input[name="u_name]').val();
$loop.find('input[name="final_name]').val(name);
break;
case '2':
var gender = $loop.find('input[name="u_gender]').val();
$loop.find('input[name="final_gender]').val(gender);
break;
case '3':
var email = $loop.find('input[name="u_email]').val().val();
$loop.find('input[name="final_email]').val(email);
break;
}
});
$(".button_action").bind('click', function(){
var $loop = $(this).closest('.loop');
var u_name = $loop.find('input[name="final_name]').val();
var u_gender = $loop.find('input[name="final_gender]').val();
var u_email = $loop.find('input[name="final_email]').val();
alert(u_name);
});

Related

The php value from the database is not being passed when the button is clicked

So I got most of my php and jquery working but I am currently stuggling on one thing which is how do I pass a db value in a while loop on button click to the jquery? At present nothing is being printed
<?php
...
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr'>".
"<button id='button' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).on("click", "#button", function(){
var name = '<?php echo($row['name']); ?>';
alert(name);
});
</script>
Say there are like seven of these boxes and the user clicks on the fourth one - how do I get that row name, like pass that to the jquery?
Ok, we need to change a few things. Every element in the HTML DOM needs a unique id. If more than one element has the same id, the machines get very confused. This is understandable, since you're saying hey pay attention to the button with the id #button! And it's like, which one? There are 7. We can add a unique id to each button during the loop by using the id from the current row the loop is fetching from the db. NB that in HTML, element ids cannot begin with a number. That's why I used button-45,etc.
We can also change the listener to listen to a class of buttons instead of a specific button - that way if any button on the page with the right class gets clicked, the listener hears it. Using jQuery you can also add data directly to the element, and retrieve is using .data(). I've provided two variables in the javascript so you can see the results of each approach.
<?php
...
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr-".$row['id']."'>".
"<button id='button-".$row['id']."' data-id='".$row['id']."' class='btn btn-success btn_calc'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
$i++;
}
?>
<script type="text/javascript">
$(document).on("click", ".btn_calc", function(){
var id_only = $(this).data('id'); //this gets us the id
//you can log values to the console, then right-click and inspect to see the results:
console.log("id_only = ",id_only);
//this gets the text into a variable
var text = $('#usr-'+id_only).val();
console.log("text = ", text);
//alert(text);
});
</script>
try the following
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr_" . $i . "'>".
"<button id='button_" . $i . "' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
$i ++;
}
}
You're problem is that you are trying to pass data in STRING FORMAT.
In your script you pass the $row out of while loop so it doesn't pass anything useful for you. If you have more than one button you can't use ID ATTRIBUTE but you have to use CLASS. Set a data-id attribute so you can pass the value from the database and set an ID to the input so you can take its value also. Try this:
<?php
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs`-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='input-" . $row["id"] . "'>".
"<button data-id='". $row["id"] . "' class='mybutton btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).ready(function(){
$(".mybutton").on("click", function(){
var myid = $(this).attr('data-id');
var myinput = $('#input-'+myid).val();
alert("MY ID IS: " + myid);
alert("MY INPUT VALUE IS: " + myinput);
});
});
</script>

Alerting only 1st Product Code from table?

So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?
ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}
As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle

php/javascript change inline label after DB update

this is my first post.. my question probably is very simple but i cannot find the right way..!
I have a php page with a query selection from a database to show many records, for each record i've put form with some fields need to be updated and a "save" button
so for each record i have a column in the result table containing a form like:
$code = "<td><form method='POST' action='mypage.php' target='_blank' />";
$code .= " <input type='hidden' name='function' value='formtaglieok' />";
$code .= " <input type='hidden' name='email' value='".$email."' />";
$code .= " <input type='hidden' name='main' value='".$main."' />";
..... some other editing fields
$code .= "<input type='text' name='field1' value='' size='2' />"
..... some other editing fields
$code .= "<td><input type='submit' value='Save' /></td>"
after this column i've put label that i want to change after pressing the button and the updating of the record, like:
$code .= "<td><div id='<this_record_id>' ></div></td>";
in mypage.php i have the php code to update the record:
function updaterecord($_POST){
...connection to db, prepare the query etc..
$stid = OCIParse($conn, $query);
if (OCIExecute($stid)) {
$res .= "Saved ";
} else {
$res .= "Error";
}
echo $res;
}
obviously, with this kind of form action and the target "_blank", i see in a new page the result "Saved" or "Error" and the updating of the record in DB is ok
The thing i would is not put "Saved" in a new page, but update the div this_record_id beside the "save" button
so, i'll try to add the onClick event to the submit button
<input type='submit' value='Save' onclick='jSaved(<this_record_id>)' />
and put this code in the head of the page
<script type='text/javascript'>
function jSaved(bcode){
document.getElementById(bcode).innerHTML = 'Saved';
}
</script>
and it updating the label correctly but opening also another page.
what i would to do is executing my updating function inside the JS code using the $_POST array, so don't get a new page but only the result of the function in the label..
someone can help me?
edit: SOLVED
1) my php main page with a form like (IMPORTANT set the form_id):
$code = "<form name='frm_".$record['TD001_SEQ']."' id='frm_".$record['TD001_SEQ']."' action='' />";
$code .= " <input type='hidden' name='function' id='function' value='formtaglieok' />";
$code .= " <input type='hidden' name='email' id='email' value='".$email."' />";
$code .= " <input type='hidden' name='main' id='main' value='".$main."' />";
$code .= " <input type='hidden' name='store' id='store' value='".$store."' />";
$code .= " <input type='hidden' name='valuta' id='valuta' value='".$valuta."' />";
....other fields
//the code for the button (not submit)
$code .= "<td><input type='button' value='Save' onclick='jSaved(".$record['TD001_SEQ']."); '/></td>";
//the label DIV with the same reference of the form/record updating
$code .= "<td><div id='res_".$record['TD001_SEQ']."' ></div></td>";
2) the javascript code
function jSaved(td001){
//searching for exact form from the document page
var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
if(document.forms[i].id == "frm_" + td001) {
form = document.forms[i];
}
}
//create a string containing all key/values from the form (parameters)
length = form.length;
var sParams = "";
for(var i = 0; i < length; i++) {
//will be key1=val1&key2=val2 ....
sParams = sParams + form.elements[i].id + "=" + form.elements[i].value + "&";
}
//execute the php update function with params in POST, td001 is needed to write le DIV label after update
var updResult = updateRecord("upd.php", sParams, td001);
}
//ajax code
function updateRecord(strUrl, params, idDiv) {
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', strUrl, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.send(params);
xmlHttpReq.onreadystatechange = function() {
/*state evaluation
* 0 - UNINITIALIZED
* 1 - LOADING
* 2 - LOADED
* 3 - INTERACTIVE
* 4 - COMPLETE*/
//state complete
if (xmlHttpReq.readyState == 4) {
//updating the DIV label with upd.php result
document.getElementById('res_' + idDiv).innerHTML = xmlHttpReq.responseText;
}
}
return resUpd;
}
</script>
3) the upd.php page
if (isset($_POST)) {
funFormTaglieOK($_POST);
} else {
echo "Denied";
}
function funFormTaglieOK($params){
global $dbdw_usr, $dbdw_pwd, $dbdw_SID;
// Try to connect to Oracle
if ($conn = OCILogon($dbdw_usr, $dbdw_pwd, $dbdw_SID)) {
//execute record update
if (recordupdate is ok){
echo "Update"
} else {
echo "Error"
}
}
}
Ok so you should use ajax, and don't use target=_blank.
If you want a new window, you can still open that by Javascript.
In Your PHP code which is called by an ajax call, you should return the right results in a JSON format. You have to parse that string in JS, and do your DOM update accordingly.

javascript function accepts [object HTMLFormElemen] instead of passed value

When I'm passing a form id to JavaScript function, the actual value what is passed there is not a string but [object HTMLFormElement].
Here is the code of a JavaScript:
function hideSowDiv(id) {
alert(id);
if (document.getElementById(id).style.display == "none") {
document.getElementById(id).style.display = "block";
} else {
document.getElementById(id).style.display = "none";
}
}
and it is a php part of the code:
while($ProductList = mysql_fetch_array($GetUers)){
echo "<div >";
echo "<input type='submit' name='OpenBtn' value='+' onclick='hideSowDiv(ItemUnit".$ProductList[0].")' > ";
echo "<span >".$UserList[4]." </span>";
echo "</div>";
//echo "<div id='".$UserList[0]."' style='display:none;>";
populateUserDivs($ProductList[0]);
//echo "</div>";
}
function populateUserDivs($Id){
$List_Query = "SELECT * FROM product WHERE product_id = ".$Id.";";
$GetList = mysql_query( $List_Query, $Connection ) or die("ERROR".mysql_error());
while($Output_List = mysql_fetch_array($GetList))
echo "<form id='ItemUnit".$UserId."' name='ItemUnit".$UserId."' method='POST' style='display:none;' >";
echo "<span class='AddingForm' > Name*: </span> <input type='textbox' name='UserName' class='Text_boxes' value='".$Output_List[1]."' required> ";;
echo "<input type='submit' name='EdtItem".$Output_List[0]."' id='DelItem".$Output_List[0]."' value='save' '>
echo " </form>";
}
}
So I wonder what am I doing wrong that the form id is not being passed to the JavaScript function, but the [object HTMLFormElement] instead.
The reason I'm passing the form id is if I put the form inside a div, the submit button is being treated just like an image and form is not working at all.
So if somebody can point me how can I turn the [object HTMLFormElement] into the form id I will be really grateful.

Updating value of textbox getting value from first text box only

I have cart page in which text box is present for updating quantity, I'm using jquery to listen to the click event & get the values of productid & the textbox. Productid I'm getting fine but value of textbox always is the value in first textbox.
Here is the code of cart file
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Here is the code for javascript.
<script>
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity').val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});
Can anyone help calling the value of particular textbox & not from the first one only?
Added dynamic id for the quantity filed - id='quantity_".$row["productid"]."' and mapped the same in javascript var quantity = $('#quantity_'+productid).val();.
In PHP
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity_".$row["productid"]."' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Javascript:
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});

Categories