Updating id with javascript - javascript

Hi I am super new to php and coding in general and I have a question about updating my attribute with javascript. I currently have a loop which cycles through various assignmentNames. I need to update the id = popup-1 in order to have the loop be functional. Appreciate any help. Here is the PHP and script I have currently:
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "Assignments";
while($row = mysqli_fetch_array($result)){
echo '<div class="popup" id="popup-1">';
echo '<div class="overlay"></div>';
echo '<div class = "content">' . $row['dueDate'] . $row['className'] . '</div>';
echo '<div class="close-btn content" onclick="togglePopup()">×</div>';
echo '<div class = "btn-group">' . '<button onclick="togglePopup()">' . $row['assignmentName'] . '</button>' . '</div>';
echo '</div>';
echo '<script type="text/javascript">','updateId();','</script>';
}
}
function updateId() {
//initialize the index with 1, the item with 0 index is already in webpage.
var i = 1;
//Add after the element
var oldID = document.getElementById("popup-1");
oldID.id = "popup-1"+i;
//Increment the index
i++;;
}

Related

Can i pass array to an HTML? Creating a dynamic html table with php/javascript

I have created a table with 3 columns and rows with the size of an array pulled from the database. I have got the value but I want to create a button inside the cells with the name from pname and when you click that button it will take you to the value of plink. I tried using <input type="button" value=" " onclick="window.open( )", but it doesn't seem to pass the arrays. I am sure there is an easier/ better way to do it with JavaScript, but I am not familiar with JavaScript. Please help me out. Here is my code.
I want the format 3 columns and infinite rows(based on the data).
<!DOCTYPE html>
$pname = array();
$plink = array();
$results = $wpdb->get_results("SELECT name, link FROM `wptable`);
if(!empty($results)) {
foreach($results as $row){
$pname[] = $row->name;
$plink[] = $row->link;
}
}
$num = 0;
echo "<table class='table'>";
echo "<tbody>";
echo "<br><br>";
$quant_row = count($pname)/3;
$quant_col = 3;
for ($count_row = 0; $count_row < $quant_row; $count_row++)
{
echo "<tr>";
for ($count_col = 0; $count_col < $quant_col; $count_col++)
{
echo "<td>";
echo $plink[$num];
echo "</td>";
$num++;
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
You just need to echo a button inside an anchor:
echo '<button type="button">' . $pname[$num] . '</button>';
try this.
echo "<td>";
echo "<button onclick=\"Document.getElementById('link$num').display=state$num? 'none' :'block';state$num=!state$num; \">". $pname[$num] ."</button><div id='link$num'>". $plink[$num]."<div>";
echo "";
when you click on $pname , you show the $plink. reclick and hide the content

Filter HTML table by comparing <select> value to column value (PHP, HTML, Javascript)

I have a dropdown <select> HTML menu created from a MySQL table using PHP. Each <option> value contains a socket, I have a HTML table created from a MySQL table using PHP which contains a column "Socket". I want to filter the table to only show matching sockets to the one selected in the <select> menu.
I have tried modifying Javascript search code to no success.
The code for the table creation is:
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td><a href='https://au.pcpartpicker.com/product/".$row["id"]."' target='_blank'>" . $row["name"]. "</a></td><td>" . $row["price"]."</td><td>" . $row["socket"]."</td><td>" . $row["chipset"]."</td><td>" . $row["ramslots"]."</td><td>" . $row["maxram"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
The code for the <select> menu is:
$sql = "SELECT name, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value='CPU'>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='".$row["socket"]."'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
Here is the link to the entire webpage code: pastebin.com/WztPQzRG
cpu SQL fiddle: db-fiddle.com/f/teZxiaduNVjuYCj1pWjj73/0
motherboard SQL fiddle: db-fiddle.com/f/pSs8yKNrgTqtiwdTbmWcg/0
Update: Here is my PHP
$sql = "SELECT name, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value=''>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["socket"] . "'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr data-socket="'. $row['socket'] . '"><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['socket'] . '</td><td>' . $row['chipset'] . '</td><td>' . $row['ramslots'] . '</td><td>' . $row['maxram'] . '</td></tr>';
}
echo "</table>";
} else {
echo "0 results";
}
Update 2:
I have tried troubleshooting by adding:
echo "<option value='AM4'>AM4</option>";
echo "<option value='LGA1151'>LGA1151</option>";
And
echo "<tr data-socket='AM4'><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
However nothing happens still. All I can think is the script isn't added right or something; here it is:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tr[data-socket]').show();
if (socket.length) {
$('tr[data-socket!="' + socket + '"]').hide();
}
});
</script>
</body>
</html>
What other troubleshooting steps can I take?
I need to get a Javascript function which runs whenever a new option is selected from the <select> menu, the function needs to get the selected <select> menu socket name then loop through each row in the table and check if the socket matches, otherwise hide the row.
Start by adding something into the table row to identify the socket. Let's use a data attribute:
echo '<tr data-socket="'. $row['socket'] . '"><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['socket'] . '</td><td>' . $row['chipset'] . '</td><td>' . $row['ramslots'] . '</td><td>' . $row['maxram'] . '</td></tr>';
Also change your default option line to this
echo "<option value=''>CPU</option>";
I'm going to suggest that you use jQuery because it's going to make your life easier. So add just before the close of your body tag
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then you need to create a listener for the select to change and then hides anything that doesn't match the selected CPU socket. Put this right AFTER the script tag above that included the jQuery library.
<script>
$(function() {
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tr[data-socket]').show();
if (socket.length) {
$('tr[data-socket!="' + socket + '"]').hide();
}
});
});
</script>

Undefined index after json_decode

I have a problem when I'm trying to get the contents of a JavaScript Array and pass its value to a PHP Array Variable.
What I'm doing is that, when a user clicks a button, the value of the item clicked will be added to the javascript array and every time the javascript array updates, the PHP variable will also update and so the contents of the div displaying the contents of the PHP array. I'm not using forms for this matter but buttons
However, when I try to use the json_decode function to get the values of a JavaScript array, it's giving me a Message: undefined index: data error
I'm a beginner in JavaScript, jQuery and AJAX so please bear with me
This is my code:
<script>
// ARRAY VARIABLE WHERE ITEM VALUES WILL BE STORED
var food_item = new Array();
// FUNCTION TO BE TRIGGERED WHEN USER CLICKED THE BUTTON, GET THE ITEM'S VALUE AND ADD IT TO ARRAY
function addToTray(data){
food_item.push(document.getElementById(data).value);
dataString = food_item; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "main",
data: {data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
}
</script>
<body>
...
// LINE OF CODE RESPONSIBLE FOR FETCHING JAVASCRIPT ARRAY VALUES
$this->session->userdata['food_tray'] = json_decode($_POST['data']);
// DIV TO BE UPDATED
<div class="col-md-3 food-tray" id="food-items" style="margin-top: 7%">
<!--FOOD TRAY-->
<div class="panel-heading">
<h3 class="ft-header">Food Tray</h3>
</div>
<div class="panel-body">
<?php
$count_fi = count($this->session->userdata('food_tray'));
echo "<p>Your Items (" . $count_fi . ")</p>";
if($count_fi == 0){
echo "<p class='no-avail-list'>NO ITEMS ADDED IN FOOD TRAY</p>";
}else{
echo "<table class='table borderless'>";
for($i = 0; $i < $count_fi; $i++){
echo "<tr>";
echo "<td>" . $this->session->userdata['food_tray'][$i] . "</td>";
echo "<td>P 200.00</td>";
echo "<td><form method='post'><input type='number' name='qty' min='1' max='100' value='1'/></form></td>";
echo "</tr>";
}
echo "</table>";
echo "<a href='' class='btn btn-success' data-toggle='modal' data-target='#myModal'>
Add Friend</a>";
echo "<a href='".base_url()."index.php/CheckOut' class='btn btn-warning'>Proceed to Checkout</a>";
}
?>
</div>
</div>
...
<?php
foreach($query->result() as $row){
echo "<div class='col-lg-7'>";
echo "<div class='thumbnail'>";
$file_name = strtolower(preg_replace('/[^A-Za-z0-9\-.]/', '', $row->name));
/*if(file_exists(FCPATH . '/assets/images/main/food/' . $file_name . '.jpg')){
echo "<img src='".base_url()."/assets/images/main/food/".$file_name.".jpg' alt='' width='320px' height='100px'>";
}else{
echo "<img src='http://placehold.it/320x150' alt=''>";
}*/
echo "<img src='http://placehold.it/320x150' alt=''>";
echo "<div class='caption'>";
echo "<h5 class='pull-right'>&#x20B1 " . $row->price . "</h5>";
echo "<h5><a href='#'>" . $row->name . "</a></h5>";
echo "<h5>Calorie Count : " . ($row->calorie_count == NULL ? "Not Available" : $row->calorie_count) . "</h5>";
// BUTTON FOR `addToTray()` FUNCTION
echo "<button class='btn btn-primary' id='".$row->id."' value='".$row->name."' style='width:100%' onclick='addToTray(".$row->id.")'>Add to Tray</button>";
// var_dump($row->name);
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
</body>
Anyone who knows how to solve this problem? Any help would be appreciated.
create your session as
$array = array ('food_tray' => json_decode($javascriptarray));
$this->session->set_userdata($array);
check if your javascript libraries are loaded in sources tab.

Show specific text from a php loop of database results using jquery

I have selected data from my database and I have looped through the results to display them on my page. I have 3 results which are shown. Each result has a button with an id called decrease. When I click this button, an alert with the name of the item containing the alert button should be displayed. I am using jQuery to achieve this.
My problem is that whenever I click the button, the name of only the first item in the results array is displayed. The buttons in the other two results don't seem to work. What am I doing wrong?
The code that loops through the result and displays the items in the database table:
if(mysqli_num_rows($run) >= 1){
while($row = mysqli_fetch_assoc($run)) {
$name = $row['name'];
$quantity = $row['quantity'];
$price = $row['price'];
$image = $row['image'];
$category = $row['category'];
$total = $price * $quantity;
echo "<div class=\"post-container\">\n";
echo "<div class=\"post-thumb\">\n";
echo "<img src='$image'>\n";
echo "</div>\n";
echo "<div class=\"post-title\">\n";
echo "<h4 style=\"font-weight:bold;\">\n";
echo "$name\n";
echo "<span id=\"deletion\">Delete</span>\n";
echo "</h4>\n";
echo "</div>\n";
echo "<div class=\"post-content\">\n";
echo "<ul style=\"list-style-type:none;\">\n";
echo "<li>Cost Per Item: <span id=\"cost\">$price</span>/=</li>\n";
echo "<li>\n";
echo "Quantity: \n";
echo "<button type=\"submit\" id=\"decrease\" class=\"glyphicon glyphicon-minus\" title=\"Decrease Quantity\"></button>\n";
echo "\n";
echo "<span id=\"cost\" class=\"quantity\">&nbsp$quantity&nbsp</span>\n";
echo "\n";
echo "<button type=\"submit\" id=\"increase\" class=\"glyphicon glyphicon-plus\" title=\"Increase Quantity\"></button>\n";
echo "</li>\n";
echo "<li>Total Cost: <span id=\"cost\">$total</span>/=</li>\n";
echo "</ul>\n";
echo "</div>\n";
echo "</div>";
}
}
And here's the jquery:
$("#decrease").click(function(){
var name = $(this).parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text();
alert(name);
});
Your HTML markup is invalid as there can be only one element with given id - id must be unique. You can use classes instead, for example class decrease will have selector .decrease, that will pertain to all your buttons.

JavaScript dropdown menu does not work in IE8

I'm using an on change for a drop down menu to display information once a choice is chosen from the dropdown. This works fine in Firefox and Chrome but I have been hoodwinked into having to use ie8 and this on change does not seem to fire. Any help would be much appreciated. Its a mix of php and html the lower part is js which outputs info when chosen.
echo "<p><h2> To View a Route: </h2><br> Pick a routes name from the list and all its information can be viewed below the selection box.</p>";
echo "<p><FORM METHOD=\"post\" ACTION=\"controller.php\">";
echo "<select class=\"toggle-data\" name='selectallrouteinfo'>";
echo "<option value=\"\">Choose a Route </option>";
for ($i = 0; $i < sizeof($list1); $i++) { //going through each element of array and outputting route
if (is_string($list1)) {
echo "<option value=\"\" data-toggle = \"$id1\" >$list1</option>";
} else {
$space = " ";
$id = $list4[$i];
$id1 = "#" . $list4[$i];
echo "<option data-toggle = \"$id1\" value=\"$id\">" . $list1[$i] . $space . $id . "</option>";
$idHolder[$i] = $id; //array for holding ids so that it passing the correct id to my loops below
}
}
echo "</select></form></p>";
for ($k = 0; $k < sizeof($idHolder); $k++) { //my outer loop is going through the ids, fitting correct id to the div and dbm obj
echo "<div id=\"$idHolder[$k]\" style=\"display: none;\">
";
$allRouteInfo = $DBM1->getAllRouteData($idHolder[$k]);
for ($j = 0; $j < sizeof($allRouteInfo); $j++) { // my inner loop is going through each element of array and outpting all route info
if (is_string($allRouteInfo)) {
echo $allRouteInfo; //if theres no info, there is no array, it has returned a string
} else {
echo $allRouteInfo[$j]; //if there is arry, happy days
}
}
echo "</div>";
//below is a js/jquery script for outputting my choice in the select of route info
echo " <script>$('.toggle-data').on('change', function() { //jquery for printing my valuable info on change
var toggle = this.options[this.selectedIndex].getAttribute('data-toggle'),
toggle_class = 'unique_classname';
$('.'+toggle_class+', '+toggle).toggle().removeClass(toggle_class);
$(toggle).addClass(toggle_class);
}); </script>";
echo " </div>";

Categories