Clear input field value after javascript alert - javascript

I have a dynamic field that get value from database, and I want to check one of the field value if it was greater from the old value or not. If it does greater, i have to give an alert and reset field value back to ''
i want to do it without using document.GetElementById because the field was looped by foreach, I'm tryin to work with document.GetElementByName but got no where. here's my code
<?php foreach ($items->result_array() as $row){ ?>
<tr>
<td><p><?php echo $row['nmbr']; ?> </p>
<p><?php echo $row['urai']; ?><p> </td>
<td><?php echo $row['jml']?> </td>
<td><div class="oldprice"><?php echo $row['oldprice']?></div></td>
<td><input id="pnwrn" class="pnwrn" type="text" name="pnwrn[]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
<td><div class="output"></div></td>
</tr>
<?php } ?>
and this is my javascript :
<script type="text/javascript">
$('.pnwrn').on('change', function () {
var twrn = $(this).val();
var price = parseInt($(this).data('harga'));
var jmlh = parseInt($(this).data('jumlah'));
if (twrn <= jmlh){
$(this).parents('tr').find('.output').html(twrn*price);
}
else {
alert("Price can not be greater from old price");
cleartext();
}
});
function clearInputs() {
document.getElementByName("pnwrn").value = "";
}
</script>
can someone help me?

You are not supposed to have multiple elements with the same id. Instead, try this:
<td><input id="pnwrn<?php echo $row['some_id_field_that_you_have']; ?>" class="pnwrn" type="text" name="pnwrn[<?php echo $row['some_id_field_that_you_have']; ?>]" value="" data-harga="<?php echo $row['jml']?>" data-jumlah="<?php echo $row['oldprice']?>"/></td>
You can also attach the matching ID on the <tr>, or to other elements, which makes it trivial to find the appropriate elements.
Unfortunately, with names like urai, harga, jumlah and pnwrn, it is extremely hard to pinpoint what exactly you're trying to do, thus just vague hints.
But - if you're trying to clear the very field you're checking, you already have it, so no lookup needs to be done. Just do clearInput(this).

Try this to loop through all the inputs and match on the class you want:
$("input").each(function (i) {
if ($(this).prop("class") === "pnwrn") {
$(this).val('');
}
});

Related

How to show input type text after submit if checkbox checked

I GOT 2 Questions
1)
So, below is the code that will keep user's checkbox checked after user submitted the form, so that he know which one he had checked and dont need to fill again.
But the question is it did not show the array, i guess is the
echo ($_POST['ao']);
I tried use print_r,but it show out all the array, i just want to echo out the specific item that user checked.Currently it just echo "Array".
2)
It did now display the input type text if user is checked after submit.But before submit, it works.
function ao1Function(){document.getElementById("ao1").value =
document.getElementById("ao1").disabled = false;
document.getElementById("ao1").style.display = "inline-block";}
function ao1Function2(){document.getElementById("ao1").value = document.getElementById("ao1").style.display = "none";
document.getElementById("ao1").disabled = true;
}
<input type="checkbox" name="cbox[]" value="Basic Add To Cart,0" onclick="if(this.checked){ao1Function()}else{ao1Function2()}"
<?php if (isset($_POST['cbox']) && in_array("Basic Add To Cart,0",$_POST['cbox'])){echo 'checked';}?>>
Basic Add To Cart<div id="ao1" style='display:none;'>
<input type="text" id="ao" min="0" step="0.05" name="ao[]" onchange="force2decimals(this)" onkeypress='validate(event)' inputmode='numeric' placeholder="Amount (RM)"
value="<?php if(isset($_POST['ao'])) echo ($_POST['ao']);?>" <?php if(isset($_POST['cbox'])) echo "style='display:inline-block;'";?>></div>
1) Here's how to show only the selected check-boxes
var_dump(array_filter($_POST['ao'], function($v) {return $v == 'true';}));
2) The JavaScript part looks OK. You might need a little fix on the PHP side and it will work perfect.
before:
<?php if(isset($_POST['cbox'])) echo "style='display:inline-block;'";?>
after:
<?php if(isset($_POST['cbox'])) echo "style='display:inline-block;'"; else echo "style='display:none;'";?>

How to get class array index for getElemetByClass name in JavaScript

everyone. I'm still new using JavaScript, I need your help to fix my problem, I try to disable checkbox after submitted. Because my checkbox value is from DB and the data will show as long as the DB have it so I'm using class="select_DB[]" in my input tag. From my knowledge class is using array index so I want to disable the checkbox that I choose I have to get the array index of the class. So how I can get the array index of the checkbox ? Need you help
//this code for disable checkbox after submit need improve I don't know how to get array index of the class
function closeCB() {
document.getElementByClassName("select_DB").disabled = true;
}
<tbody>
<?php
include "db_connect.php";
$sql_select = $dt_bas->prepare("SELECT id_pegawai, nm_pegawai, tmp_lahir FROM pegawai");
$sql_select->execute();
while($row = $sql_select->fetch(PDO::FETCH_ASSOC)){
$id = $row["id_pegawai"]; // id
$nm = $row["nm_pegawai"]; // employe name
$tmp = $row["tmp_lahir"]; // birthday
?>
<tr>
<td><input type="checkbox" class="select_DB[]" class="select_DB[]" value=<?php echo"$id";?> <?=was_checked($id)?>/></td> <!-- This is the checkbox-->
<td><?php echo "$id";?></td>
<td><?php echo "$nm";?></td>
<td><?php echo "$tmp";?></td>
<td>
Ubah
Detail
</td>
</tr>
<?php } ?>

PHP get input value without submit

Guys i have foreach loop where i list some prices. All price have own input radio button.
By default only one price from looping is checked. I want to get that value when page is lodaed.
I have one session where i store number of days. Based on these days I get the price of cars.
$numDays = $_SESSION['days']; // 5
$calculate_km = $numDays * 140; // 5*140km
So in page where i want to show total KM i use:
if(isset($_SESSION['days']) {
$numDays = $_SESSION['days'];
}else {
// Show default selected radio button value
}
Problem is bcs price list with radio is on the some page and there is no sumbiting
My loop:
<?php if($prices = getCarPricePeriod($car->ID, $od, $do)):?>
<?php $first = true; ?>
<?php foreach ($prices as $price): ?>
<tr>
<td><input type="radio" name="price" value="<?= $price['value'];?>" <?= $first ? 'checked' : '' ?>> </td>
<td><input type="text" name="price_name" value=" <?= $price['name'];?>">€/per day</td>
</tr>
<?php endforeach; ?>
<?php $first = false; ?>
<?php endif; ?>
Total KM : <span> <?= $numDays * 140 ;?> </span>
Only is posible to get that value if i submit that form. So i need js for this or any way to do this in php
I want to get that value when page is lodaed.
Use .ready() , selector $("tr input:checked") , .val()
$(document).ready(function() {
var val = $("tr input:checked").val()
})
If what you are asking is "how to send data from client-side to server-side", then the answer is AJAX.
Take a look at W3School's AJAX tutorial here: http://www.w3schools.com/ajax/
EDIT 1
for javascript, this should do it:
document.querySelector("input[type=radio]:checked").getAttribute("value")
Without submit, you need JavaScript to do that, like this:
<script>
var p = document.getElementByName("price");
</script>

changing data output with onchange event

I have an option box which lists the users of something in my site. I then have two input boxes. One for wins and another for losses. I am trying to create an onchange event, so that whenever a certain user is selected from the option box, the php will output that users info. As of now the output is not changing. What am I doing wrong with my onchange event?
function myFunction() {
var wins_var = document.getElementById('wins');
var losses_var = document.getElementById('losses');
}
PHP that outputs the data and html with inputs
if ($stmt = $con->prepare("SELECT * FROM team_rankings WHERE user_id=user_id")) {
$stmt->execute();
$stmt->bind_result($ranking_id, $ranking_user_id, $ranking_firstname, $ranking_username, $ranking_division, $ranking_wins, $ranking_losses);
//var_dump($stmt);
if (!$stmt) {
throw new Exception($con->error);
}
$stmt->store_result();
echo "<select name = 'member' onchange='myFunction()'>";
while ($row = $stmt->fetch()) {
echo "<option value = '{$ranking_user_id}' data-wins = '{$ranking_wins}' data-losses = '{$ranking_losses}'";
echo ">{$ranking_firstname}</option>";
}
echo "</select>";
} else {
echo "<p>There are not any team players yet.</p>";
}
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage();
}?><br><br>
<label>Wins
<input type="text" value="<?php echo $ranking_wins; ?>" id="win">
</label>
<label>Loss
<input type="text" value="<?php echo $ranking_losses; ?>" id="losse">
</label>
You're on the right lines, and you don't need to do any Ajax just to achieve what you asked in your question.
The main problem is that in your Javascript, you get a reference to the two inputs for wins and losses, but you don't actually assign any value to them.
Assuming you're using jQuery (as you tagged it), then it's much easier to use this for the onchange binding and value assignments.
Firstly, you just need to make sure your "member" select has an ID instead (or as well) as a name, and you don't need the "onchange" as we'll bind that with jQuery:
echo "<select id = 'member'>";
Then, your Javascript just needs to look like this:
$(document).ready(function() {
$("#member").change(function() {
myFunction();
});
myFunction();
});
function myFunction() {
$selectedOption = $("#member option:selected");
$("#wins").val($selectedOption.data("wins"));
$("#losses").val($selectedOption.data("losses"));
}
The initial $(document).ready() function sets up the onchange binding to call myFunction(), and the second myFunction() call just ensures the wins and losses inputs are populated for the default selected option on the initial page load.
JS Fiddle here: http://jsfiddle.net/fa0kdox7/
Oh yes, and finally, your wins and losses inputs just need to look like this:
<label>Wins
<input type="text" value="" id="wins">
</label>
<label>Loss
<input type="text" value="" id="losses">
</label>
Note that I corrected a couple of typos in their IDs.

Post value change

I have records which column name is counter. And the value is like 000003, 000012, and so on. But my problem is, when I try to post it the value that receive in the form action url change, I receive only 3 which is the real value is 000003. Why is that? I echo POST value in my second page.
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result1 = $mysqli->query("
SELECT *
FROM app
");
echo'<table border=1>
<thead>
<tr>
<th>cc</th>
</tr>
</thead>';
echo'<tbody>';
while($row = $result1->fetch_assoc()){
echo' <tr>';
echo "<td><a href='#' onclick='javascript:postIt(".$row['counter'].");'>".$row['counter']."</a></td> ";
echo'</tr>';
}
echo "</tbody></table>";
?>
<script>
function postIt(value){
document.forms[0].id.value = value;
document.forms[0].submit();
}
</script>
<form name="blah" action="check.php" method="post">
<input type="hidden" name="id">
</form>
Why 000003 become only 3, or 000172 become 172. Help?
this may work
echo "<td><a href='#' onclick='javascript:postIt(\"".$row['counter']."\");'>".$row['counter']."</a></td> ";
Because you are working with integers, not string. If you want to keep them as strings, meaning, with the leading zeros, convert the values to string type.
Why is this a problem? At the receiving end you can simply pad the number back out how you want it to.
It seems like a counter should be an integer. You can then pad it out or not if and when you want to.
If you really want to you can pad it out before you send it.
See here:
How can I pad a value with leading zeros?

Categories

Resources