Star rating system created through loop - javascript

enter image description hereI have a table that displays a list of recipes from a database. Each recipe stores a rating out of 5. If no ratings has been submitted 'Not yet rated' will display. If a recipe has a rating, for example, 3, I would like 3 stars to appear. I have wrote jquery to try to achieve this but it works for the first recipe and not for the rest. For each recipe, more stars are printed. Any ideas where I'm going wrong?
if ($avg !=0)
{
define('RATE_RECIPE_MAX_STAR_RATING', 5);
$contentitems1 = "<form><div class='stars'>";
for ($i = 1; $i <= RATE_RECIPE_MAX_STAR_RATING; $i++)
{
//$contentitems1 .= '<input type="radio" style= "display:none;"
//$contentitems1 .= '<img class="rate_recipe_star" name="star_' . $i . '" id="star_' . $i . '" src="fadedstar.png" width="25" />';
$contentitems1 .= '<span class="fa fa-star-o star" name="star_' . $i . '" id="star_' . $i . '"></span>';
}
"</div></form>";
echo $contentitems1 .="<script type='text/javascript'> paint_the_stars($avg)
</script>";}
echo '<div class="star_' . $avg . '"></div>'?>
function paint_the_stars(howmany) {
var items = new Array();
$(".star").each(function() {
//var star = jQuery(this)
var star = $(this);
console.log(star);
var starno = $(star).attr('id').substring(5);
console.log(starno);
//console.log("Star:"+star);
if (starno <= howmany) {
//console.log("TRUE PRINT A STAR"+starno);
//$(this).attr('src', 'yellowstar.png');
var item = $(this).removeClass("fa-star-o").addClass("fa-star");
items.push(item);
} else {
//return true;
var item = $(this).removeClass("fa-star").addClass("fa-star-o");
items.push(item);
}
if (starno == 5) {
$.each(items, function(){
console.log(this);
$('.star_'+howmany).append(this);
});
return false;
}
})
}

Related

Javascript - perform operation vertically and horizontally with dynamic text input

need help i am working with some text inputs here that are dynamic depending on how many the user enter. what i wanted to do is to compute the text inputs automatically after user input value using onkeyup javascript.
here the php and html code:
<?Php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply()' id='tb1'>";
echo "x";
echo "<input type='text' onkeyup='multiply()' id='tb2'>";
echo "=";
echo "<input type='text' onkeyup='multiply()' id='tb3'>";
echo "<br>";
}
?>
total:<input type='text' onkeyup='multiply()' id='tb4'>
and here's the javascript:
<script>
function multiply(){
var textbox1 = document.getElementById('tb1').value;
var textbox2 = document.getElementById('tb2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb3').value = result;
}
}
</script>
now, the first row of text inputs works fine but the remaining text inputs doesn't I know i'm missing something here and i can't figure it out, how can
i compute horizontally those values from tb1 and tb2 then display it on tb3
and compute vertically all the values of tb3 and display it in tb4. any help is much appreciated.TIA
Well all rows contain elements with same ids. So row 1 will contain elements with ids: tb1, tb2, tb3. Row 2 will also contain elements with ids tb1, tb2 and tb3.
The id of each element on a page needs to be unique. You can make the ids unique by appending the row number to the id. For example:
<?php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-1'>";
echo "x";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-2'>";
echo "=";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-3'>";
echo "<br>";
}
?>
Total: <input type='text' id='tb4'> <input type='button' onclick='CalculateSum()' title='Calculate Sum'>
Your JavaScript code will then look as follows:
<script>
function multiply(row) {
var textbox1 = document.getElementById('tb' + row + '-1').value;
var textbox2 = document.getElementById('tb' + row + '-2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb' + row + '-3').value = result;
}
}
function CalculateSum() {
let total = 0;
for (let i=0; i < 10; i++) {
total += document.getElementById('tb' + i + '-3').value;
}
document.getElementById('tb4').value = total;
}
</script>

Php id recognizing in js

I have a loop in php and I'm using a js function onclick to get the id from the php loop. I do loop in js to recognize a php dynamic id, but it recognizes the wrong order of the loop item.
Sample php code:
$list = 1;
for ($i = 0; $i < 7; $i++ ){
$listNo = $list;
$list++;
$html .= "<div class='row l'>";
$html .= " <div class='col-xl-3 col-lg-8 col-6'>
<input name=']' id='dm_slider_img_url_$listNo' type='text' value='" . $dm_slides[++$counter] . "'/>
<button class='set_custom_images' id='meta-image-button-$listNo'>
<span class='dashicons dashicons-plus-alt'></span>
</button>
</div>
<div class='col-xl-1 col-lg-4 col-6 mr-auto'>
<img id='dm_slider_img_preview_$listNo' src='" . $dm_slides[$counter++] . "' name=''>
</div>";
$html .= "</div>";
}
Sample js code:
var send_attachment_bkp = wp.media.editor.send.attachment;
for (let ids=1; ids<8; ids++) {
if ($('#meta-image-button-'+ids).length > 0) {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor) {
$(document).on('click', '.set_custom_images', function(e) {
e.preventDefault();
var button = $(this);
var id = button.prev();
wp.media.editor.send.attachment = function(props, attachment) {
$('#dm_slider_img_url_'+ids).val(attachment.url);
$('#dm_slider_img_preview_'+ids).attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
};
wp.media.editor.open(button);
return false;
});
}
}
}
What am I doing wrong?
After looking other questions related to getting id, I figured it out. After calling click function using button class, I stored it as variable and added this variable.
$(document).ready(function() {
var $ = jQuery;
// var ids = 1;
// $(«.set_custom_images»).onclick = function(t) {t.attr(«id»)}
var send_attachment_bkp = wp.media.editor.send.attachment;
if ($("[id^='meta-image-button-']" ).length > 0) {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor) {
$(document).on('click', '.set_custom_images', function(e) {
var clickedID = this.id;
e.preventDefault();
var button = $(this);
var id = button.prev();
wp.media.editor.send.attachment = function(props, attachment) {
$('#dm_slider_img_url_'+clickedID).val(attachment.url);
$('#dm_slider_img_preview_'+clickedID).attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
};
wp.media.editor.open(button);
return false;
});
}
}
});
And in php make some changes
$list = 1;
for ($i = 0; $i < 7; $i++ ){
$listNo = $list;
$list++;
$html .= "<div class='row l'>";
$html .= " <div class='col-xl-3 col-lg-8 col-6'>
<input name='' id='dm_slider_img_url_m_$listNo' type='text' value='" . $dm_slides[++$counter] . "'/>
<button class='set_custom_images' id='m_$listNo'>
<span class='dashicons dashicons-plus-alt'></span>
</button>
</div>
<div class='col-xl-1 col-lg-4 col-6 mr-auto'>
<img id='dm_slider_img_preview_m_$listNo' src='" . $dm_slides[$counter++] . "' name=''>
</div>";
$html .= "</div>";
}
I hope this will help for someone who searches solution like this

localstorage data not persisting between pages

I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});

Update php SQL when checkbox check (no submit button)

I am pulling data out of a database and displaying in a table. I would like my checkbox, when checked/unchecked, to auto-update the value in the database without using a submit button to trigger the action. I'm new to AJAX and tried to adapt some code. I cannot get it to work. One major thing I don't understand is what '#state_span' is for?
Data Page (HTML)
$sql = "SELECT * FROM Orders ORDER BY " .$order;
$myData = mysqli_query($dbconnect, $sql);
while ($record = mysqli_fetch_array($myData)){
if ($record['Sent'] == 0) {
$sent = "";
} else {
$sent = "checked";
}
if ($record['Paid'] == 0) {
$paid = "";
} else {
$paid = "checked";
}
echo "<tr>";
echo '<td class="MenuLeft">' . $count . "</td>";
echo '<td class="MenuMid">' . $record['Name'] . "</td>";
echo '<td class="MenuRight"><input type="checkbox"
name="Sent"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $sent . ' ></td>';
echo '<td class="MenuRight"><input type="checkbox"
name="Paid"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $paid . ' ></td>';
echo "</tr>";
echo '<script>
$(document).ready(function() {
$(".ChkSwitch").click(function() {
var id = this.id;
var col = this.name; //Tell us what column to update
var state = this.checked ? 1 : 0;
$("#state_span").load("ChkUpdate.php?d="+id+"&col="+col+"&state="+state);
}
}
</script>
';
PHP
$id = $_GET['id'];
$state= $_GET['state'];
$col= $_GET['col'];
include("dbconnect.php");
$query = "UPDATE Orders SET '$col' = '$state' WHERE ID = '$id' ";
mysqli_query($dbconnect, $query);

ReferenceError: Function Not Defined. What am I missing?

Can't seem to figure out why I keep getting this ReferenceError: OnLoad is not defined error.
Since the time of my previous commit, I have changed lines 28-30 and that is all.
How can this cause my javascript to not be loaded properly? I have only changed these three lines. I'm certain these lines shouldn't really be related. The Javascript file is identical to the one in the previous commit.
What am I missing?
UserInterface.php - Current Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$CurrDB_Obj = $this->ParentAppInstance->CurrentDBObj; //Line 28
$EncodedFields = json_encode($CurrDB_Obj->GetFields()); //Line 29
echo "<body onload='OnLoad($EncodedFields);'>"; // Line 30
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.php - Previous Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT); //Line 28
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num]; //Line 29
$EncodedFields = json_encode($CurrDBSet_Obj->GetDBSetFields()); //Line 30
echo "<body onload='OnLoad($EncodedFields);'>";
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.js
var DBSetFields = [];
var NumQBoxes = 3;
//window.onload = OnLoad();
function OnLoad(Fields){
console.log("OnLoad called");
CloneDBSetFields(Fields);
var RMNodeList = document.getElementsByClassName('RMButton');
for (var i = 0; i < RMNodeList.length; ++i) {
console.log(RMNodeList[i]);
RMNodeList[i].onclick = RemoveQBox; // Calling myNodeList.item(i) isn't necessary in JavaScript
}
}
function JSTEST(){
window.alert("JS Called Successfully!!");
}
function CloneDBSetFields(Fields){
console.log("CloneDBSetFields");
DBSetFields = Fields;
}
function SwitchDatabaseSet(MainPageDoc){
document.getElementById("DebugOutput").innerHTML = "Test";
window.location.replace('/GLS_DBSearchProject/index.php?DBSet=' + document.getElementById("DBSetSelector").value);
console.log(document.getElementById("DBSetSelector").value);
//console.log(document.)
}
function Fields_FOREACH(ELEMENT, INDEX, ARRAY){
console.log("TEST");
var FieldOption = document.createElement('option');
FieldOption.setAttribute('value', ARRAY[INDEX]);
FieldOption.innerHTML = ARRAY[INDEX];
this.appendChild(FieldOption);
}
function AddQueryBox(){
NumQBoxes += 1;
var NewQBox = document.createElement('div');
NewQBox.setAttribute('class', 'QueryBox');
//Create and fill Field Selector dropdown "select" element
var FieldSelector = document.createElement('select');
FieldSelector.setAttribute('name', 'Field_' + NumQBoxes);
//foreach element in Fields
console.log(DBSetFields);
DBSetFields.forEach(Fields_FOREACH, FieldSelector);
//Create and fill
var QueryText = document.createElement('input');
QueryText.setAttribute('type', 'text');
QueryText.setAttribute('name', 'Query_' + NumQBoxes);
//Create "-" Remove button for removing query lines.
var RemoveButton = document.createElement('button');
RemoveButton.innerHTML = "-";
RemoveButton.setAttribute('type', 'button');
RemoveButton.setAttribute('class', 'RMButton');
RemoveButton.addEventListener("click", RemoveQBox);
//Combine the individual elements into a new query box and insert the new query box into the HTML Document
NewQBox.appendChild(FieldSelector);
NewQBox.appendChild(QueryText);
NewQBox.appendChild(RemoveButton);
document.getElementById("QFormBody").insertBefore(NewQBox, document.getElementById("add"));
}
function RemoveQBox(e){
console.log("Remove");
var RemoveButton = this; //this == e.currentTarget
console.log(RemoveButton);
var QBox = RemoveButton.parentNode;
QBox.remove();
NumQBoxes -= 1;
}
EDIT: My Javascript file is not being loaded on the client side (ie. it doesn't show up under "Sources", so I'm not really not sure: Why wouldn't my javascript be loading on the client side?

Categories

Resources