changing data output with onchange event - javascript

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.

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 do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.
The checkboxes look like:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid
The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.
The reason is it's displayed in a loop with output like this:
<tr>
<td><input type="checkbox" class="deletefunc" value="<? echo $mid; ?>"></td>
<td><input type="checkbox" class="star" value="1"> <!-- jquery/ajax onclick function --></td>
<td><a href></td>
<td><form name....><input type="submit" value="something"></form></td>
<tr>
So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....
And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.
I would do it like this:
HTML:
<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>
JS:
$(function() {
$('#delete-them').on('click', function() {
var data = $('.deletefunc').attr('name', 'delete[]').serialize();
$.ajax('delete-them.php', {
method: 'POST',
data: data,
success: function() {
alert('deleted!');
}
});
});
});
PHP:
<?php
$ids = $_POST['delete'];
$params = array_fill(0, count($ids), "?");
$sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
//DELETE FROM some_table WHERE id IN(?,?,?,?);
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$stmt = $pdo->prepare($sql);
$stmt->execute($ids);
?>
So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.
We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.

Clear input field value after javascript alert

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('');
}
});

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Pass checkbox value to Edit (using href)

I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']

Categories

Resources