How can I get the values in the while loop using button with js?
<?php
while ($row = mysqli_fetch_array($query))
{
echo '<input type="text" name="sample" value="'.$row['sample'].'">';
}
?>
Thanks
You can get the value of textbox when you click on a button.
<input type="text" name="sample[]" value="abc" class="valueInput">
<input type="text" name="sample[]" value="xyz" class="valueInput">
<input type="text" name="sample[]" value="pqr" class="valueInput">
<input type="button" class="getValue" value="Get Value">
Note: I have set the static input box you can make it dynamic but make sure please add the class as valueInput.
Jquery Code.
$(document).on('click','.getValue',function(){
var valArr = [];
$(".valueInput").each(function(){
valArr.push($(this).val());
});
console.log(valArr);
})
The name of the input field should indicate an array with [].
<form action="action.php" method="POST">
<?php
while ($row = mysqli_fetch_array($query)){
echo '<input type="text" name="sample[]" value="'.$row['sample'].'">';
}
?><input type="submit">
</form>
action.php: (Processes the data on submit)
<?php
echo "<pre>";
print_r($_POST['sample']);
echo "</pre>";
Related
I have a problem in automating a form with hidden inputs in PHP. Basically I'm doing an input for a barcode scanner where the user will input the barcode and it will auto-submit, just like in a cash registry.
The conflict which I think is the cause of the problem is because of a conditional form. Here is a snippet:
<form method="post" id="form1">
<div class="products">
<input type="text" name="code" class="form-control" autofocus required onchange="submit()" />
</div>
</form>
<?php
$query = 'SELECT * FROM product WHERE PRODUCT_CODE='.$code.' GROUP BY PRODUCT_CODE ORDER by PRODUCT_CODE ASC';
$result = mysqli_query($db, $query);
if ($result):
if(mysqli_num_rows($result)>0):
while($product = mysqli_fetch_assoc($result)):
?>
<form id="form2" method="post" action="pos.php?action=add&id=<?php echo $product['PRODUCT_CODE']; ?>" >
<input type="hidden" name="quantity" class="form-control" value="1" />
<input type="hidden" name="name" value="<?php echo $product['NAME']; ?>" />
<input type="hidden" name="price" value="<?php echo $product['PRICE']; ?>" />
<input type="submit" name="addpos" style="margin-top:5px;width: 462px" class="btn btn-info" value="Add"/>
</form>
<?php
endwhile;
endif;
endif;
?>
<script>
function submit() {
document.getElementById("form1").submit();
}
document.getElementById("form2").submit();
</script>
The data from form1 has no trouble auto-submitting, then the form2 will auto-submit but nothing happens. I need help on how can I make form2 auto-submit correctly too. I have tried different event handling for form2 but nothing happens. I only know a little bit of javascript so that's just how my script turned out.
Thank you, Programming kings!
Because the second form is inside the while loop, if there are multiple results there will be multiple forms with the same id = "form2".
You need an increment variable $incrm = 2 inside the loop,
form id='form<?php echo $incrm;?>',
with $incrm++ before ending it. I also recommend to add ann onchange event to the last input 'price' ; onchange = submit(this).
function submit(inp) {
inp.parentElement.submit();
}
I'm working on the code displaying in the while loop data received from the database. Within that code there is a form in which I added a hidden input (name="position"). I'd like to use that input to store number of pixels from the top of the window. Unfortunately, the javascript added by me, changes the value of the hidden input only in the last table in the loop. In the first tables the hidden input named "position" remains unchanged (remains empty). Could anyone please help me?
<?php
while ($row = $wynik->fetch_assoc()) {
?>
<form method="post" style="margin-bottom: 0px;" onsubmit="poz()">
<input type="hidden" name="edition" value="<?php echo $row["id"]; ?>">
<input type="hidden" id="<?php echo $row["id"]; ?>" name="position" value="">
<input type="submit" value="Edytuj" class="edytuj">
</form>
<script>
function poz() {
var position = window.pageYOffset;
document.getElementById(<?php echo $row["id"]; ?>).value = position;
}
</script>
You need to add an event listener to know what is clicked
window.addEventListener("load",function() {
[...document.querySelectorAll(".edytuj")].forEach(function(elem) {
elem.addEventListener("click",function (e) {
var tgt = e.target;
tgt.previousElementSibling.value=tgt.offsetTop;
})
});
})
<input type="hidden" name="edition" value="<?php echo $row["id"]; ?>">
<input type="hidden" id="<?php echo $row["id"]; ?>" name="position" value="">
<input type="button" value="Edytuj" class="edytuj">
I am creating an input field using foreach loop like this
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
$data is Array
(
[0] => Array
(
[asset_id] => abc-02
[asset_name] => Freezer
)
[1] => Array
(
[asset_id] => xyz-01
[asset_name] => Refrigerator
)
[2] => Array
(
[asset_id] => 300001
[asset_name] => Generator
)
)
and in javascript, I am trying to get the value using this code but it always alerts first value of the input.
<script type="text/javascript">
$(document).ready(function () {
var typename = $('#typename').val();
alert(typename);
});
</script>
i have to disable this input field when value is 'Generator'
Try:
$('[readonly].form-control').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>
.val() called once will always produce only one value; .val() docs:
Get the current value of the first element in the set of matched elements .
HTML id attribute is supposed to be unique, try this instead.
<?php
$count = 0;
foreach($data as $key=>$val) {
?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:
$('[id^="typename_"]').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
</td>
Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.
You should never use same id for several elements.
Update you code for debug, and you'll see that you have an array:
<script type="text/javascript">
$(document).ready(function () {
var typename = $('[name="model[]"]')
.toArray().map(e => e.value);
alert(JSON.stringify(typename));
});
</script>
You should update your php, to set different id for each element drawn in a cycle, i.e:
<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
So you'll be able to address eash input separately:
var typename = $('#typename_1').val();
Use class instead of duplicate id like this.
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery loop your class and get value using this instant..
$(document).ready(function () {
$( ".clsValue" ).each(function( index ) {
var typename = $(this).val();
alert(typename);
});
});
try this ,
this will call alert function for each input with form-control class
$(document).ready(function () {
$(".form-control").each(function(){
alert($(this).val());
})
});
Set class="typename" instead of id="typename":
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
You can get values like this:
<script type="text/javascript">
$(document).ready(function () {
var typename1 = $('.typename')[0].val();
var typename2 = $('.typename')[1].val();
alert(typename1);
});
</script>
there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.
Please let me know if you need sample code.
pure js approach;
replace id with class;
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
js
window.onload = alertTypeNames();
function alertTypeNames() {
document.getElementsByClassName('typename').map((inputTag) => {
alert(inputTag.value);
return true;
});
}
you fired with your id that's why it's fired only first element value.
this is how you can do that with your current code
$(document).ready(function () {
$('input[name="model[]"]').each(function(){
alert($(this).val());
});
});
However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.
<script type="text/javascript">
$(document).ready(function () {
$('.common-class').each(function() {
alert($(this).val());
});
});
</script>
<?php $incr_var = 1; ?>
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.
http://api.jquery.com/live/
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1 status">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery
$(document).on('change','.status',function(){
var $status = $(this).val();
if($status == 'not_working'){
$(this).closest('tr').find('.reason').removeAttr('disabled');
}
});
reason is class you have to give which input field you want to disable
I have to click on the update button and then do an update in database and a refresh to show the updated values on the same page. These values must be updated in the database as well. I have been trying to do the refresh but it does not work. Need some help and guidance. Is there any other alternative besides page refresh? Can it be done without page refresh?
<?php
//initalizing the query
$id = $_GET['id'];
$query = "SELECT * FROM new_default_reports WHERE id = '$id'";
$result = $conn->query($query);
$row = $result->fetch_assoc();
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" onclick="window.location.reload();"/>
</form>
</div>
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
header("Refresh: 0; url=previewgraphs.php?id=".$id);
}
?>
UPDATED:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="previewgraphs.php?id=$id" method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
Please take updated value from the database after update query.
Please try this code :-
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
$select_query = "SELECT * FROM new_default_reports where id = $id";
$select_result= $conn->query($select_query );
$row = $select_result->fetch_assoc();
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
The header function does not work in your case because you have already output before trying to set the header.
The solution is to reverse the php and html code such that the php code is on the very beginning of the document.
Little side note, now you actually do not need the refresh anymore.
EDIT included select query.
<?php
if (isset($_POST['set'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
//header("Refresh: 0; url=previewgraphs.php?id=".$id);//not needed
$select_query = "SELECT sql_statement, x_xis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
$row = $select_result->fetch_assoc();
}
}
?>
<input type="button" id="btnShow" style="overflow:hidden;margin- left:1400px;font-weight:bold;background-color:lightgray" value="Edit Default Reports" />
<div id="dialog" align="center">
<form action = "" method="post">
<label> SQL Statement</label>
<textarea name="sqlst" style="width:100%;height:40%;" class = "form-control"><?php echo $row['sql_statement']?></textarea><br>
<label> X axis: </label>
<input type="text" name="x" class = "form-control" value="<?php echo $row['x_axis'] ?>"><br>
<label> Y axis: </label>
<input type="text" name="y" class = "form-control" value="<?php echo $row['y_axis'] ?>"><br>
<input type="submit" name = "set" value="Update" style="background-color:darkred;width:100px;color:white;font-weight:bold" />
</form>
</div>
And remove onclick="window.location.reload();"
Here is how I would do it:
<input type="button" id="btnShow"
style="overflow:hidden; margin-left:1400px; font-weight:bold; background-color:lightgray" value="Edit Default Reports">
<div id="dialog" align="center">
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<label>SQL Statement</label>
<textarea name="sqlst" style="width:100%; height:40%;" class="form-control">
<?php echo $row['sql_statement']?>
</textarea>
<br>
<label>X axis: </label>
<input type="text" name="x" class="form-control"
value="<?php echo $row['x_axis'] ?>">
<br>
<label>Y axis: </label>
<input type="text" name="y" class="form-control"
value="<?php echo $row['y_axis'] ?>">
<br>
<input type="submit" name="set" value="Update"
style="background-color:darkred;width:100px;color:white;font-weight:bold"">
<input type="submit" name="submitted" value="Submit the form">
</form>
</div>
<?php
if (isset($_POST['submitted'])){
$query = "UPDATE new_default_reports SET sql_statement ='{$_POST['sqlst']}', x_axis ='{$_POST['x']}', y_axis = '{$_POST['y']}' where id = $id";
$result = $conn->query($query);
// make a query to get the updated result and display it on the page
$select_query = "SELECT sql_statement, x_axis, y_axis FROM new_default_reports WHERE id = $id";
$select_result = $conn->query($select_query);
if ($select_result->num_rows == 1) {
echo "You have successfully updated the database.";
$row = $select_result->fetch_assoc();
echo $row['sql_statement'];
echo $row['x_axis'];
echo $row['y_axis'];
}
}
?>
So you wouldn't need to refresh the page, but rather you send the form to itself. It will result in another request. If the form has been sent the php code in the if-clause get executed and the database will be updated. Than you have the task to make a select query to get the updated result and display it on the page.
Should the user open the page with the form per get request, she is not going to see any results from the database.
When writing HTML you should also try to be consistent and keep the code conventions throughout your project. For single tags XML-like style is <input \>, HTML-style is <input>.
I hope this helps you and also gives you some alternative view how to solve your problem.
EDIT:
I removed the onclick event from your input element and added a submit button. When checking if the form has been sent, look for the submit button in your if-clause. If you like you can use <button type="submit">Submit the form</button> instead of <input type="submit">
ANOTHER EDIT:
I added simple select query and displayed the updated report on the page.
This is my idea about it:
user sends GET request - form is displayed
user sends POST request (submitting the form) - it is sent to itself, the from is displayed and the user gets feedback if update was successful, the udpated values being displayed
When creating something like this I always think on CRUD - create, retrieve, update, display.
The form should update an entry in the database.
For the retrieve part you should better use another view, displaying only the result, but not the form.
You could certainly send the form to the page where the result is displayed*, but I think that would be a bad practice. The user needs some feedback if the update action was successful.
for example something like this:
<form action="<?php echo 'previewgraphs?id=$id'; ?>">
You shouldn't squeeze to much logic into one part. Rethink your design. I'd also reccomend you to use a framework that implements the MVC pattern. You have a big choice. The framework will take care about many things and provide you also semantic URLs, so you'll have something like:
/reports
/reports/1
instead of appending all the parameters to the URL.
first restructure your code.
The first part of your code must save the values in case changes are being submitted. Then you read from the database again and show results.
However this could be a browser or proxy caching problem. I have a couple of tags that have been very helpful:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta http-equiv="cache-control" content="no-cache">
put them in the html < head > section . Older IEs do weird things with proxys sometimes.
Cheers, Karsten
I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}