I have searched for several hours now trying to implent scripts to change the div background. I've found this solution which works when it's not in a loop:
Javascript: onClick checkbox change div color
The challenge here is that the checkboxes is in a foreach loop with unique id values.
Here is my code:
<script language="JavaScript" type="text/JavaScript">
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#0000FF';
} else {
x.style.backgroundColor = '#FF0000';
}
}
</script>
<style type="text/css">
#result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
</style>
</head>
<body>
<?php
$SL = 0;
foreach($results_resultat as $key => $row_resultat) { ?>
<div id="result">
<input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(result, this)">
</div>
<?php } ?>
With this code it will show all the rows which are selected from the tabel but it won't change the div color when clicking the checkbox.
Help is very much appreciated. :-)
You're using the same id result to wrap all your checkbox elements. ids should be unique, use class="result" instead to wrap your checkbox elements. Plus, you don't have to send anything except this to myFunction function. So change your code in the following way,
CSS
.result {
background-color: #FF0000;
padding: 7px;
margin: 7px;
}
PHP
<?php
$SL = 0;
foreach($results_resultat as $key => $row_resultat) { ?>
<div class="result">
<input type="checkbox" name="res_id[]" value="<?php echo $row_resultat['id']; ?>" onChange="myFunction(this)">
</div>
<?php
}
?>
JavaScript
function myFunction(_this) {
if (_this.checked) {
_this.parentElement.style.backgroundColor = '#0000FF';
} else {
_this.parentElement.style.backgroundColor = '#FF0000';
}
}
The problem with your code is that line: onChange="myFunction(result, this)".
At that line result is not defined, usually it is common to pass a string with selector, or string with an id.
Something like that onChange="myFunction('result', this)"
And then in you JS function use document.getElementById to get a reference to the DOM element.
<script language="JavaScript" type="text/JavaScript">
function myFunction(id, _this) {
if (_this.checked) {
document.getElementById(id).style.backgroundColor = '#0000FF';
} else {
document.getElementById(id).style.backgroundColor = '#FF0000';
}
}
</script>
Related
I have created a progress bar. Value is being fetched from database. Now i want to categorize the colour of progress bar like if width value is below 50 so progress bar colour is red. If value is above 50 and below 90 colour is blue if value is 100 then colour is green.
progress bar is display in table cell. and values are fetched from database
<tr class="success">
<td><?php echo "$row->ID"; ?></td>
<td><?php echo "$row->name"; ?></td>
<td><div class="progress" style = "height:24px;width:200px">
<div class="progress-bar" id = "newprogress" role="progressbar" aria-valuenow="<?php echo "$row->Percentage"; ?>" style = "width :<?php echo "$row->Percentage"; ?>%";>
<?php echo "$row->Percentage" ?>%
</div>
</div>
<td>
as i have tried one of the solution here
$(document).ready(function(){
var bar = parseInt($("#newprogress").width());
if (bar >= 90) {
$("#newprogress").removeClass("bckColor").addClass("bar-success");
}
else if (bar >= 50 && bar < 90) {
$("#newprogress").removeClass("bar-success").addClass("bckColor");
}
});
I think you selected the wrong element.
$(document).ready(function() {
var bars = $('.progress-bar');
for (i = 0; i < bars.length; i++) {
console.log(i);
var progress = $(bars[i]).attr('aria-valuenow');
$(bars[i]).width(progress + '%');
if (progress >= "90") {
$(bars[i]).addClass("bar-success");
} else if (progress >= "50" && progress < "90") {
$(bars[i]).addClass("bar-warning");
} else {
$(bars[i]).addClass("bar-error");
}
}
});
.progress {
width: 200px;
height: 24px;
border-radius: 10px;
background-color: #F1F1F1;
margin-bottom: 10px;
}
.progress-bar {
border-radius: 10px;
height: 24px;
display: block;
}
.bar-warning {
background-color: yellow;
}
.bar-success {
background-color: green;
}
.bar-error {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress" style="heigt:24px;width:200px">
<div class="progress-bar" name="progress" role="progressbar" aria-valuenow="90"></div>
</div>
<div class="progress" style="heigt:24px;width:200px">
<div class="progress-bar" name="progress" role="progressbar" aria-valuenow="30"></div>
</div>
<div class="progress" style="heigt:24px;width:200px">
<div class="progress-bar" name="progress" role="progressbar" aria-valuenow="50"></div>
</div>
Try below code.
$(document).ready(function(){
var bar = parseInt($('.progress').width());
if (bar >= 90){
$(".progress").removeClass("bckColor").addClass("success");
}
else if (bar >= 50){
$(".progress").removeClass("success").addClass("bckColor");
}
});
.bckColor {
background-color: blue !important;
}
.success {
background-color: green !important;
}
Use the Below code I have named sample.php
Here the value will be collected from the another file data.php and changes the color according to the condition provided
Languages Used: HTML,PHP, JS
sample.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<?php require_once('data.php'); ?>
<script>
var myVar = setInterval(inter, 1000);
function inter() {
document.getElementById("boot").style.width =
<?php echo $x; ?>+"%";
document.getElementById("boot").innerHTML =
<?php echo $x; ?>+"%";
if (
<?php echo $x; ?>< 90)
{
document.getElementById("boot").className = "progress-bar progress-bar-danger";
}
else
{
document.getElementById("boot").className = "progress-bar progress-bar-success";
}
}
</script>
</head>
<body>
<table>
<td>
<div class="progress" style = "height:24px;width:200px">
<div name="progress" role="progressbar" id="boot" aria-valuenow="
<?php echo'$row->Percentage';?>" >
</div>
</div>
</td>
</table>
</body>
</html>
Here is data.php
Results:
I realise you were asking for a JavaScript solution, but this can be achieved (somewhat) in PHP.
You are already working with variables in the PHP script to set values for your HTML output, so why not do the same for the colour of your progress bar?
This example uses the default Bootstrap colours, but you can substitute others if you require:
// Value retrieved from the database. This can be a percentage (which may be easier
// to work with or just use the raw value depending on your needs)
$valueFromDatabase = 9;
// This will give us a green bar, 9% wide.
// Use the switch command to set the output colour (using the Bootstrap
// default colours Primary, Warning, Danger, Success etc. Set these as you need.
switch ($valueFromDatabase) {
case ($valueFromDatabase <= 10):
$bar_colour = "success";
break;
case (($valueFromDatabase > 10) && ($valueFromDatabase <= 30)):
$bar_colour = "warning";
break;
case ($valueFromDatabase > 30):
$bar_colour = "danger";
break;
}
// Now we use $bar_colour to set the colour in the output below.
// Width set to the value retrieved from the database
echo "<div class='row'>\n
<div class='col-md-12'>\n
<h4>Your Progress Bar</h4>\n
<div class='progress md-progress pos-rel' style='height:25px'>\n
<div class='progress-bar progress-bar-$bar_colour progress-bar-striped' style='width:$valueFromDatabase%; height: 25px'>
<span style='line-height: 25px'>$valueFromDatabase%</span>
</div>\n
</div>\n
</div>\n
</div>\n";
I am trying to get the result from "headline" and "content" to show up one at a time and then fade in and out to the next result in a loop. Currently, it shows all the results at once and the fades in and out and then show all the results again. Any idea on how to get them to show one at a time TIA
<html>
<head>
<style>
#table1{/*table aspects and design */
border:1px solid #FFFFFF;
background:#FFFFFF;
display:none;
width: 60%;
margin-left: auto;
margin-right: auto;
}
th{/*align table headers*/
text-align:center;
}
td,th{
border:1px solid #FFFFFF;
text-align:center;
}
</style>
</head>
<table id="table1" cellpadding="5" cellspacing="1" width="50%">
<? if ($query=$pdo->prepare("SELECT * FROM `Announcements_Current`"))
{
/* select all information from the table and take it into the page */
$query->execute();
while ($result = $query->fetch(PDO::FETCH_ASSOC)){
$head = $result['headline'];/*puts result of headline from table into variable*/
$content = $result['content'];
/*puts result of content from table into variable*/
echo /* echo the table to display announcements*/'
<tr>
<th>
<h1>
'.$head.'
</h1>
</th>
</tr>
<tr>
<td>
<font size="4">
'.$content.'
</font>
</td>
</tr>';
}
}
?>
</table> <!--end of table-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
/* define script for jquery*/
for (var i = 0; i < 500; i++) {/* for loop to fade in and out the announcements*/
$(document).ready(function() {/*function to fade table in and out*/
$('#table1').fadeIn(2000);
$('#table1').delay(5000);
$('#table1').fadeOut(2000);
}
)};
</script>
You're going about this the wrong way.
This won't be a complete solution. I'll try to hopefully make you understand the logic behind doing this yourself.
Loop through the results but instead of echoing them immediately, save them in arrays:
<?php
$head[] = $result['headline'];
$content[] = $result['content'];
?>
After the loop, only echo the first results. Add some IDs to your <h1> and <td> while you're at it. You'll need them later.
Then pass the arrays to JavaScript:
<script type="text/javascript">
var head = '<?= json_encode($head); ?>';
var content = '<?= json_encode($content); ?>';
</script>
Now that you have the arrays in JS, you have to iterate through them and for each value, change the content of your <h1> and <td>:
for (var i = 0, len = head.length; i < len; i++)
{
document.getElementById("H1_element_ID").innerHTML = head[i];
document.getElementById("TD_element_ID").innerHTML = content[i];
}
You can probably throw your fadeIn(), delay() and fadeOut() in this loop, to achieve your desired result!
Finally, delete your for and put this one inside $(document).ready().
I found an example online that shows how to build a auto-suggest text field by using javascript and PHP. Originally I started out by building my on version of the example, but after many failed attempts in getting it to work, I decided to see if the example itself even worked. I copied and pasted the example, changing only the database connection and the information regarding the database table. To my surprise the example still doesn't work! In my database I have a a table called Device and in that table there are three columns, ID,Device_type, and Price. Right now I have one value in the table and it's Apple iPhone 6 in the Device_type column, so when the program is working correctly, it should start to auto suggest Apple iPhone 6 as soon as I type "A" into the text box. Unfortunately, that doesn't happen, a dropdown box appears, as it should, but the box is blank and doesn't show any suggestions.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Suggestion Example</title>
<style type="text/css">
<!--
div.suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
text-align: left;
}
-->
</style>
<script type="text/javascript">
var nameArray = null;
</script>
</head>
<body onclick="document.getElementById('divSuggestions').style.visibility='hidden'">
<?php
mysql_connect("hostname", "username", "password") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DeviceRecycling');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo("<script type='text/javascript'>");
echo("this.nameArray = new Array();");
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
<!-- --------------------- Input Box --------------------- -->
<table border="0" cellpadding="0" width="50%" align="center">
<tbody align="center">
<tr align="center">
<td align="left">
<input type="text" id="txtSearch" name="txtSearch" value="" style="width: 50%; margin-top: 150px; background-color: purple; color: white; height: 50px; padding-left: 10px; padding-right: 5px; font-size: larger;" onkeyup="doSuggestionBox(this.value);" />
<input type="button" value="Google It!" name="btnGoogleIt" style="margin-top: 150px; background-color: purple; color: white; height: 50px; font-size: larger;" onclick="window.location='http://www.google.com/#hl=en&source=hp&q=' + document.getElementById('txtSearch').value" />
</td>
</tr>
<tr align="center">
<td align="left">
<div class="suggestions" id="divSuggestions" style="visibility: hidden; width: 50%; margin-top: -1px; background-color: purple; color: white; height: 250px; padding-left: 10px; padding-right: 5px; font-size: larger;" >
</div>
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function doSuggestionBox(text) { // function that takes the text box's inputted text as an argument
var input = text; // store inputed text as variable for later manipulation
// determine whether to display suggestion box or not
if (input == "") {
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
} else {
document.getElementById('divSuggestions').style.visibility = 'visible'; // shows the suggestion box
doSuggestions(text);
}
}
function outClick() {
document.getElementById('divSuggestions').style.visibility = 'hidden';
}
function doSelection(text) {
var selection = text;
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
document.getElementById("txtSearch").value = selection;
}
function changeBG(obj) {
element = document.getElementById(obj);
oldColor = element.style.backgroundColor;
if (oldColor == "purple" || oldColor == "") {
element.style.background = "white";
element.style.color = "purple";
element.style.cursor = "pointer";
} else {
element.style.background = "purple";
element.style.color = "white";
element.style.cursor = "default";
}
}
function doSuggestions(text) {
var input = text;
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
</script>
</body>
</html>
In my attempt to trouble shoot, I have discovered a few things. First off the connection string to the database is good, and that is not the problem. In an attempt to further check whether it was the database query that was causing issues, I have discovered that if I remove the echo("<script type='text/javascript'>") from the PHP portion of the code, that it will actually print Apple iPhone 6 at the top of the page, which tells me the query itself is actually working. Obviously though, by removing the javascript tag the program still doesn't work because it should only be displaying the results as you type something that matches what is in the database.
hi maybe you have a error on your code
this is a little example
for get the result and show
autocomplete.php
<?php
$connection = mysqli_connect("localhost","username","password","employee") or die("Error " . mysqli_error($connection));
//fetch department names from the department table
$sql = "select department_name from department";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['department_name'];
}
echo json_encode($dname_list);
?>
for view and show the result
demo.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<!-- load jquery ui css-->
<link href="path/to/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<!-- load jquery library -->
<script src="path/to/jquery-1.10.2.js"></script>
<!-- load jquery ui js file -->
<script src="path/to/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#department_name").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="department_name" type="text" size="50" />
</body>
</html>
i preffer use jquery
donwload jquery
enter link description here
result
So I have a roll over effect for my mock store, the images and info for each boxes are taking from .sql file and auto generated sections. I want it too cover each section. I could hard code it, but that's a little too draconian.
<div id="scoll" class="group">
<div class="container">
<div class="center_items">
<?php
//external pages area
include_once('config\database.php');
include_once('object/chair.php');
$database = new Database();
$conn = $database->getConnection();
$chair = new Chair($conn);
$stmt = $chair->readAll();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
?>
<div class="product_box" >
<img src="img/<?php echo $row['THUMB']; ?>" alt="chair_image"> </a>
<h4> <?php echo $row['chair_name'];?> </h4>
<p>$<?php echo $row['PRICE'];?></p>
<div class="buy-box-shadow group">
Buy me!
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
JS
onload=init;
function init() {
document.getElementsByClassName("product_box")[0].onmouseover = function(e){
e.preventDefault();
mouseOver();
}
document.getElementsByClassName("product_box")[0].onmouseout = function(e){
e.preventDefault();
mouseOut();
}
function mouseOver() {
document.getElementsByClassName("buy-box-shadow")[0].style.opacity = .9;
}
function mouseOut() {
document.getElementsByClassName("buy-box-shadow")[0].style.opacity = 0;
}
See the code is hard coded to be the first element, a tad confused on how to make it go for every element.
You don't need JavaScript for that, you can do it just with CSS.
.product_box .buy-box-shadow {
opacity: 0.9;
display: none;
}
.product_box:hover .buy-box-shadow {
display: block;
}
Should be able to do this with forEach. Like so:
function init() {
var product_boxes = document.getElementsByClassName("product_box");
product_boxes.forEach(function(currentValue, index, array){
currentValue.onmouseover = function(e){
e.preventDefault();
mouseOver();
}
});
Searched, but wasn't able to find any similar problems or solutions.
I have some templated HTML which builds a form based on data from a spreadsheet, as I have a variable number of dropdowns and options in those dropdowns.
On click of submit I want to display a spinning gif to the user, so they know it is processing.
If the backend code in code.gs passes the input through all the tests I want to update a div with a success message, if any of the checks fail with an error message.
I've got this to work, before with the create .createHtmlOutputFromFile method, but now with .createTemplateFromFile it just wipes the whole page.
HTML template
<style type="text/css">
#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600,300);
#container{
padding-left:10px;
font-family: 'Open Sans', Arial, sans-serif;
}
#header{
width: 75%;
margin: 0 auto;
text-align: center;
margin-bottom:10px;
}
form{
text-align: center;
margin-top:10px;
}
#nameField{
width:400px;
margin-bottom:10px;
}
#reqIndic{
color:#FF0000;
}
select{
margin-top: 5px;
width:150px;
}
#submit{
margin-top:20px;
width:125px;
height:40px;
}
#confirmation{
width: 30%;
margin: 0 auto;
min-height:60px;
border-radius: 5px;
}
#padding{
width: 30%;
margin: 0 auto;
min-height:60px;
border-radius: 5px;
}
</style>
<div id="container">
<div id="header">
<h2>Cheltenham Classic</h2>
</div>
<br>
<form name="projectsForm">
<span id="reqIndic">*</span>
<span> Name</span>
<input id="nameField" type="text" name="name" required>
<br>
<? for (var race in races) { ?>
<span><?= race ?></span>
<select>
<? for (var i = 0; i < races[race].length; i++) { ?>
<option value="<?= races[race][i] ?>"><?= races[race][i] ?></option>
<? } ?>
</select>
<br>
<? } ?>
<br>
<input id="submit" type="submit" value="Submit Form" onclick="google.script.run
.withSuccessHandler(updateDiv)
.onEvent(this.parentNode);spinner()">
</form>
</div>
<div id="confirmation" style ="text-align:center"></div>
<div id="padding" style ="text-align:center"></div>
<script type="text/javascript">
function updateDiv(returnValue){
alert('debug');
var div = document.getElementById('confirmation');
if(returnValue == false){
var errStr = '<p>ERROR: Please check your rankings for blank fields or multiple entries of the same project and re-submit your rankings</p>';
div.innerHTML = errStr;
}
else{
div.innerHTML = '<p>Success! Your results were submitted successfully</p>';
}
}
function spinner(){
var div = document.getElementById('confirmation');
div.innerHTML = '<img src="http://loadinggif.com/images/image-selection/32.gif">'
}
</script>
Back end code
I've cut the onEvent function right down to just returning an object with a key value pair without making any checks.
The updateDiv function runs and the alert shows then the entire page is wiped.
function doGet(){
var raceForm = HtmlService.createTemplateFromFile('RaceForm');
raceForm.races = getRaces();
return raceForm.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function onEvent(e){
return {'valid': true};
}
function getRaces(){
var url = //spreadsheet url
var wb = SpreadsheetApp.openByUrl(url);
var ws = wb.getSheetByName('Races Log');
var racesObj = {};
var wsValues = ws.getDataRange().getValues();
for(var i = 0; i <wsValues.length;i++){
var race = wsValues[i][0];
racesObj[race] = [];
racesObj[race].push('0');
for(var j = 1; j<wsValues[i].length;j++){
racesObj[race].push(wsValues[i][j]);
}
}
return racesObj;
}
Any help much appreciated.
If I hard code the racesObj object:
var racesObj = {one:["one","two"], two:["one", "two"], "races":["belmont", "kentucky"]};
The page looks like this: (Using the template)
If I click the submit button, I get this: