Only last value from JavaScript in while loop is displayed - javascript

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">

Related

Get the values of while loop using button with js

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>";

Get values from php loop and multiple those values on keyup

I have a PHP loop created dynamically with two text boxes and one result column.
What i need is , just multiple the values entering first two boxes and show result in its near Result box.
The PHP loop
<?php
$sql=$db->query("SELECT * FROM calc");
foreach($sql as $row)
{
?>
<div class="calc">
<input type="text" id="txt1id<?= $row['id'] ?>" onkeyup="multiple()">
<input type="text" id="txt2id<?= $row['id'] ?>" onkeyup="multiple()">
<input type="text" id="resultid<?= $row['id'] ?>" title="Result shows here automatically">
</div>
<?php } ?> // loop ends here.
And script is
<script>
function multiple()
{
// how to get two different variables like this with different id to multiple ?
var firstBox = parseInt(document.getElementById(firstid).value);
var secondBox = parseInt(document.getElementById(secondid).value);
}
</script>
Pass row id to the function like this
<div class="calc">
<input type="text" id="txt1id<?= $row['id'] ?>" onkeyup="multiple(<?= $row['id'] ?>)">
<input type="text" id="txt2id<?= $row['id'] ?>" onkeyup="multiple(<?= $row['id'] ?>)">
<input type="text" id="resultid<?= $row['id'] ?>" title="Result shows here automatically">
</div>
And change in JS like below
<script>
function multiple(rowid)
{
var firstBox = parseInt(document.getElementById("txt1id"+rowid).value);
var secondBox = parseInt(document.getElementById("txt2id"+rowid).value);
}
</script>

Required Entry for only one button of two

I have a form that has a text field that is a required entry for one(1) of my two(2) buttons. The first(1st) button applies a code, in the text field, to the products in the cart section of my store. The second(2nd) removes all codes from all products in the cart section.
What's the best way of going about this?
Thx.
<div id="cart-coupon-menu" class="coupon-menu-hide">
<form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/couponPost') ?>" method="post">
<div class="discount">
<div class="discount-form">
<input type="hidden" name="remove" id="remove-coupone" value="0" />
<div class="input-box">
<input class="input-text" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" placeholder="Enter a Coupon or Promo Code" autocomplete="off"/>
</div>
<div class="buttons-set">
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
<button type="button" title="<?php echo $this->__('Cancel Coupon') ?>" class="button" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel Coupon') ?>"><span><span><?php echo $this->__('Cancel Coupon') ?></span></span></button>
</div>
</div>
</div>
</form>
</div>
The above form will be serialized and set to a controller via AJAX and an appropriate response will be returned.
When the input box is null I want the input box to act as a required field and disallow submission via the first button. However, when it is null the second button should still allow for submission. When text is entered into the input box they both behave normally.
Currently i'm attempting to do something like this:
<script type="text/javascript">
//<![CDATA[
var discountForm = new VarienForm('discount-coupon-form');
discountForm.submit = function (isRemove) {
if (isRemove) {
$('coupon_code').removeClassName('required-entry');
$('remove-coupone').value = "1";
} else {
$('coupon_code').addClassName('required-entry');
$('remove-coupone').value = "0";
}
if(something where I identify if it is required and the field is null){return null;}
else{continue with ajax call;}
I think it's just a simple javascript something like:
<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="isValid() ? discountForm.submit(false) : handleInvalid()" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
I used a ternary operator in there... so basically it says if isValid() returns true, execute: discountForm.submit(false) otherwise execute: handleInvalid().
Then the javascript functions would be:
function isValid() {
var couponCode = document.getElementById('coupon_code').value;
return /* whatever logic you want here... */
}
function handleInvalid() {
// do whatever you want to the coupon_code input to indicate it's required and pop up an error message
alert("Please enter a coupon code!");
}
You should give knockout a try. It updates your view(html) according to changes in your js code. See this example.

Can only post first result of while loop

I am using a while loop to display results from a query. The while loop is working fine. In hidden fields I would like to post the values of userID and accessID to the user details page. I am submitting the form using javascript to submit from a link. My problem is that regardless of the username I click I can only post the values for the first displayed record. What am I doing wrong?
The code:
<?php
while($row = $result->fetch_array()) { ?>
<form method="post" action="edit_user.php" id="userForm">
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
</form>
<?php } ?>
The javascript used for submitting the form:
function submitForm() {
var form = document.getElementById("userForm");
form.submit();
}
Thank you.
EDIT - I don't want to pass the values in the url.
you are generating multiple <form>s inside loop, move your <form> outside while loop, like:
<form method="post" action="edit_user.php" id="userForm">
<?php
while($row = $result->fetch_array()) { ?>
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID[]" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID[]" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
<?php } ?>
Submit
</form>
You're running into trouble because of this line
var form = document.getElementById("userForm");
In Javascript and HTML, an ID is supposed to be unique to a certain DOM element. In this case, you've got a whole load of form tags that have the same ID. You need to give each form a different ID, and then pass that ID to the submitForm function.
For example:
<?php
$id = 0;
while($row = $result->fetch_array()) { ?>
$id++;
<form method="post" action="edit_user.php" id="<?php echo "userForm".$id ?>">
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
</form>
<?php } ?>
and then
function submitForm(id) {
var form = document.getElementById(id);
form.submit();
}
edit: how do I php? :D

Multiple forms onclick event only working for first form

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
}

Categories