Pass checkbox value to Edit (using href) - javascript

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']

Related

The first table row (dynamically generated) always shows, no matter the input value for Javascript

Sorry for asking, I am probably missing something small here but have no clue. I dynamically generated a long list of radio buttons using PHP. On top of the list is an HTML input to search through the list using jQuery. This works, except for one tiny detail. The first radio button in the list always shows, no matter what the search result is. Even if I type something completely different, I will always see the first radio button in the list together with the matching results.
What is going wrong here?
This is my dynamically generated list of radio buttons, using HTML and PHP:
<input id="addplantSearch" class="form-control" type="text" name="addplantsearch" placeholder="Zoek op (Latijnse) naam..." style="margin:0; height:48px;"> <!-- Search input -->
<?php
$query = "SELECT * FROM plants ORDER BY plants.name ASC;";
$post_data = $data->execute($query);
// Prepared statement in 'execute' method (Database class)
?>
<div class="addplant-list">
<?php
foreach ($post_data as $post) {
# Loop start
?>
<div class="searchable">
<label class="pselect-container"> <?php echo $post['name']; ?>
<input type="radio" name="selectPlant" value="<?php echo $post['plant_id']; ?>">
<span class="pselect-checkmark" style="width:100%;">
<img src="../system/src/img/plants/<?php echo $post['directory']; ?>/icon.png" />
<?php echo $post['name'] . " - (" . $post['name_latin'] . ")"; ?>
</span>
</label>
</div>
<?php
# Loop end
}
?>
</div>
And this is my jQuery, responsible for searching through the list:
$("#addplantSearch").keyup(function() {
var value = this.value;
$(".addplant-list").find(".searchable").each(function(index) {
if (!index) return;
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
});
EDIT: The first item in the list is determined by the alphabetical order (ASC) of my database results (see $query variable). So this is always the same item in alphabetical order.
It looks like your issue is with your if statement.
if (!index) return;
This problem occurs because JavaScript uses 0 based arrays, and 0 is also a falsy value. Meaning:
!0 === true
and the first item in the array will always return out of the function and won't be applicable to the toggle logic.
So probably a lot of ways to work around this, one would be to check the length of the array before the each function. Ex:
$("#addplantSearch").keyup(function() {
var value = this.value;
var searchableItems = $(".addplant-list").find(".searchable");
if (searchableItems.length) {
searchableItems.each(function(index) {
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
}
});

How to show an entire select element in a div using only Javascript

I'm writing a code for a project and I want to be able to show an entire select element in a div.
I can't type in the code in the result area because I am calling most of the code from a database. I have tried putting a container around the select element but it still doesn't work. The select element in my work is called from a database and there are many of them which is why I am using '$x' to make each of the select elements unique. I have searched stackoverflow and other forums online but can't find an answer relating to my problem.
//some code above here
$x = 1;
while($row = $result->fetch_assoc()){
$uidcheck = mysqli_num_rows($result);
$catname = $row['name'];
$catrefno = $row['refno'];
echo '
<label class="container"><input type="radio" name="catname[]" id="catname'.$x.'" value="'.$catname.'"> '.$catname.'
<span class="checkmark"></span></label>
<div id="selectdiv'.$x.'"><select class="form-control itnames" name="itname[]" id="itname'.$x.'" required>
<option></option>';
$sql1 = "SELECT * FROM foodarea WHERE status!='deactive' and itcatname='$catname'";
$result1 = $conn->query($sql1);
$uidcheck1 = mysqli_num_rows($result1);
if ($uidcheck1 > 0){
while($row1 = $result1->fetch_assoc()){
$uidcheck1 = mysqli_num_rows($result1);
$itname = $row1['itname'];
echo '<option>'.$itname.'</option>';
}
}
echo '</select></div>
<script>document.getElementById("catname'.$x.'").onchange = function() {
var itnames = document.getElementById("selectdiv'.$x.'").innerHTML;
var selectarea = document.getElementById("selectarea");
selectarea.innerHTML = !this.checked ? "none" : itnames;
};</script>';
$x++;
}
}
echo '<div id="selectarea"></div>'
I expect that when the radio buttons are clicked, the entire select element with id - "itname'.$x.'" is shown in the div with id - "selectarea". But it does not. Instead it shows the value first option or a javascript error. Please I am a beginner and would really appreciate the help.
Mistake is maybe here
<div class="selectdiv'.$x.'">
should be an id
<div id="selectdiv'.$x.'">

How to get either select .val() or div .text() from dynamically created elements with same id?

Depending on the user type, my page dynamically creates either a select element (for admins to change) or a div with text (for regular users) using the same id.
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher' >teacher</option>";
echo "</select></td></tr>";
}
else echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
When the page submits, I need either the .val() from the select element or the .text() from the div element.
I can't use .val() on the div element and I can't use .text() on the select element.
Is there a way in jQuery / javascript to get one or the other, depending on which element type was created?
make the else statement as so (use input[type=hidden], to use the .val())
else echo
"<tr>
<td>Type:</td>
<td>
<!-- div to show the value -->
<div>$user_type</div>
<!-- hidden input type to get the value via jQuery .val() -->
<input type='hidden' id='type' value='$user_type'>
</td>
</tr>";
Oh by the way, you can use PHP variables inside strings that are defined with double quotes echo "$someVar";
Since you are printing out from PHP the HTML out put, by the same time you can print a Javascript variable who has what method use to get the value/text. Then, use the variable in your Javascript to perform one query or other.
Something like :
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher'>teacher</option>";
echo "</select></td></tr>";
echo "<script> var method = 'val'</script>";
}
else
{
echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
echo "<script> var method = 'text'</script>";
}
You can check it with the following simple code in javascript:
if(document.getElementById("type").tagName == "SELECT") {
//Your code for admin
}
else
{
//Your code if it is not admin
}
You can have the text or the value with a simple and elegant ternary condition :
var result = $("#type").val() !== undefined ? $("#type").val() : $("#type").text();

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.

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.

Categories

Resources