How to apply css in jQuery on variable that is in loop? - php

Hello guys I search alot but find nothing regarding my problem.
I have one foreach loop in that i have one anchor tag and that will be changed according to my ifelse condition.
Now I want to change color of each if else condition in that. Please help me to do.My code is within jQuery script.
for(var j=0;j<arrayData.length;j++){
var country = "";
if(arrayData[j].key=="40"){
country = "UK";
}else if(arrayData[j].key=="41"){
country = "INDIA";
}else if(arrayData[j].key=="47"){
country = "POLAND";
}else{
country = "GERMANY";
}
check+='<a class="btn btn-success" href="<?php echo base_url()?>uploads/'+arrayData[j].value+'">'+country+
'</a>|';
}
check +='</td></tr>';

You can just append it on the html string.
for(var j=0;j<arrayData.length;j++){
var country = "";
var color = "";
if(arrayData[j].key=="40"){
country = "UK";
color = "red";
}else if(arrayData[j].key=="41"){
country = "INDIA";
color = "orange";
}else if(arrayData[j].key=="47"){
country = "POLAND";
color = "yellow";
}else{
country = "GERMANY";
color = "green";
}
check+='<a class="btn btn-success" style="background-color:' + color + ';" href="<?php echo base_url()?>uploads/'+arrayData[j].value+'">'+country+
'</a>|';
}
check +='</td></tr>';
Other option: You can also add class to <a> tag.
Like <a class="color-red">
CSS:
.color-red {
background-color: red;
}

Related

issue on Active and Deactive change color in php jquery

I want to change color of (i) tag when I click for active and Deactive.
this cole is running successfully but when i click any (a) tag change first (a) tag color also.
my css
.active{color:green;}
.deactive{color:red;}
My ajax code
$('.pactive').click(function(){
var pactiveId = $(this).attr('id');
var currentVal = $(this).find('i').attr('title');
var addCls = 'active';
var removeCls = 'deactive';
var title = 'Active';
if(currentVal == 'Active'){
addCls = 'deactive';
removeCls = 'active';
title = 'Deactive';
}
$(this).find('i').addClass(addCls).removeClass(removeCls);
$(this).find('i').attr('title',title);
$.post('controller/ajax-product-active.php?pactiveId='+pactiveId,
{},function(data)
{
$('#product-active').html(data);
});
});
ajax-product-active.php
$pactiveId = $_GET['pactiveId'];
$checkstatus = mysqli_query($conn,"select * from products where id = '{$pactiveId}'");
while($prow = mysqli_fetch_array($checkstatus))
{
if ($prow['status']=='Active') {
$update_status = mysqli_query($conn,"update products set status = 'Deactive' where id = '{$pactiveId}'");
echo "<a id='$prow[id]' class='pactive' style='cursor: pointer;'>
<i class='fa fa-circle active' aria-hidden='true' title='Active'></i></a>";
}
elseif ($prow['status']=='Deactive') {
$update_status = mysqli_query($conn,"update products set status = 'Active' where id = '{$pactiveId}'");
echo "<a id='$prow[id]' class='pactive' style='cursor: pointer;'>
<i class='fa fa-circle deactive' aria-hidden='true' title='Deactive'></i></a>";
}
}
This code is running successfully but when i click any (a) tag change color on first (a) tag also.
i want to change color only this (a) tag on click on which (a) tag.
please help
I think you need to add class in anchor tag instead of i like below:-
Jquery:-
$(this).find('a').addClass(addCls).removeClass(removeCls);
PHP:-
echo "<a id='$prow[id]' class='pactive active' style='cursor: pointer;'>
<i class='fa fa-circle' aria-hidden='true' title='Active'></i></a>";

JQUERY next () img in li? multiple imgs in li

<div id = "listwrapper">
<ul id = "mylist">
<?php
$images = glob("sorted/2017/*.jpg");
$i = 0;
foreach((array_reverse($images)) as $image){
if ($i == 0){
echo "<li>";
}
$i++;
echo'<img id="BR" src="'.$image.'">;
if($i==4){
echo"</li>";
$i = 0;
}
}
?>
</ul>
<div>
The above script works fine and outputs a <li> tag with 4 images in each one. with about 80 images in total.
Now I'm trying to use next() and closest() to display the next <img> in the <li> tag when the image is clicked. or if it is the last <img> in the <li>, then skip to the next <li>? seems like it would be easier to change the script and just put each image in its own <li> tag..
$('#mylist li img').click(function(){
var el = document.getElementById('BR');
var big = document.getElementById('BRBIG');
var img = document.getElementById('mylist li img');
imageClicked = $(this).closest('li');
big.src = imageClicked.find('img').next().next().attr('src');
$('#brbigcon').show('fadein');
$('#BRBIG').show(300);
$('#fs').show(300);
});
Is there someway to implement closest('img') instead of closest ('li')?
Try this:
<div id = "listwrapper">
<ul id = "mylist">
<?php
$images = glob("sorted/2017/*.jpg");
$i = 0;
foreach((array_reverse($images)) as $image){
if ($i == 0){
echo "<li>";
}
$i++;
echo '<img class="BR" src="'.$image.'">';
if($i==4){
echo "</li>";
$i = 0;
}
}
?>
</ul>
<div>
Jquery:
$('#mylist .BR').click(function(){
var src = $(this).attr('src');
var big = $('BRBIG');
big.attr('src', src);
$('#brbigcon').show('fadein');
$('#BRBIG').show(300);
$('#fs').show(300);
});
A piece of advice. In your html, if the amount of images is not a multiple of 4, the last li never gets closed. Here you have another approach to solve it...
<div id = "listwrapper">
<ul id = "mylist">
<?php
// Get the array of image urls.
$images = array_reverse(glob("sorted/2017/*.jpg"));
// Create the html `img` element of each image.
$imgs = array_map(function($v) { return "<img class=\"BR\" src=\"".$v."\">"; },$images);
// Chumk the array in groups of 4 and put each group inside of a `li` element.
$imgsli = array_map(function($v) { return "<li>".implode("",$v)."</li>"; },array_chunk($imgs,4));
// Print all the `li` elements.
echo implode("",$imgsli);
?>
</ul>
<div>
About the jquery, this would be my approach...
$('#mylist li img').click(function() {
var $nextImg;
if ($(this).next('img').length > 0) { // There's more img in current li, get the next one.
$nextImg = $(this).next('img');
}
else {
if ($(this).closest('li').next('li').length > 0) // There's more li's, go to the first image of the next one.
$nextImg = $(this).closest('li').next('li').find('img:first');
else // We are in the last div, go to the first image.
$nextImg = $('ul#mylist li:first img:first');
}
// Now $nextImg is the jQuery object of the right next image. Do what you need to show it.
...
});
With this you get the right next image according to your indications. Just add the code you want to show the image, etc.
I hope it helps

Create variable from table cells

I need your help to figure this out.
I have a table (link on top) of prices for typographic company. Let's say, to print business cards. My goal is to create a system where customer can press on a price and confirmation popup will appear with information from table.
For example: I need 500 business cards with Option #1.
I press on the price 740 and popup window appears with info: "You have ordered 500 business cards with Option #1 by price 740.
Manually I can create all variations like (row-1, cell-5) + (row-3, cell-1) + (row-3, cell-5) but this is not an options, even though the logic is right.
I have a table and popup already created and working. All prices are variables and I can change them from my back-end. I need help with combining variables.
How can I achieve my goal using php?
You need JavaScript to do a popup, not PHP. You can use PHP to create an array for JavaScript to use to retrieve the values.
In this example I am creating a JavaScript array ($JS) that will have the same values as the displayed table.
In the Table I add buttons to each cell (I use buttons because the default style display is inline-block and their purpose is to be clicked) where when selected will pass the row,column of the table.
$JS = 'var cells['; // initialize JavaScript array
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo "
<tr><td><button type="button" onclick="sel($ndx,0)">$row[0]</button></td>
<td><button type="button" onclick="sel($ndx,1)">$row[1]</button></td>
<td><button type="button" onclick="sel($ndx,2)">$row[2]</button></td>
<td><button type="button" onclick="sel($ndx,3)">$row[3]</button></td>
<td><button type="button" onclick="sel($ndx,4)">$row[4]</button></td><tr>";
$JS .= [$ndx[$row[0],$row[1],$row[2],$row[3],$row[4],$row[5]][";
$ndx++;
}
echo '</table>'
$JS = substr($JS,0,-1) . ']]'; // trim the trailing `[` and close the array
echo <<<EOT
<script type="text/javascript">//<![CDATA[
$JS
function sel(r,c){
var selected = cells[r,c];
}
//]]>
</script>
EOT;
The main thing I wanted to show in the above is how PHP can pass values to JavaScript. It is not really needed as you could just pass the value in the sel($ndx,0,$row[x]) where x is the column number in the table
But there is a better way that would be more user friendly:
This example the user makes selections by checking the check box. The form is submitted (to same script) for confirmation.
There is a hidden input where name=sub and value=1. so when the confirm is clicked this can be checked by checking the value of $_POST['sub']
$sub = intval($_POST['sub']);
if($sub == 1){
$selections = array();
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
}
}
// Confirmation (e.g. create popup box) code goes here
}
.
echo '<form action="???.php" method="post"><div><table>';
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo <<<EOT
<tr><td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\"/>$row[0]</div></td>
<td><div id="d$ndx1"<input type="checkbox" name=\"c$ndx1\" value=\"$row[1]\"/>$row[1]</div></td>
<td><div id="d$ndx2"<input type="checkbox" name=\"c$ndx2\" value=\"$row[2]\"/>$row[2]</div></td>
<td><div id="d$ndx3"<input type="checkbox" name=\"c$ndx3\" value=\"$row[3]\"/>$row[3]</div></td>
<td><div id="d$ndx4"<input type="checkbox" name=\"c$ndx4\" value=\"$row[4]\"/>$row[4]</div></td>
EOT;
}
echo '</table><input type="submit" value="Confirm Selections"/><input type="hidden" name="sub" value="1"/></div></form>';
To style the checked check boxes:
Add an onclick event to each check box
<input type="checkbox" name=\"c$ndx0\" value=\"$row[0] onclick=\"chk($ndx0)\" \>
Then this JavaScript will change the background color of the div which encapsulates the check box giving visual feedback to the user.
The init() function creates an array for each check box eliminating the document.getElementById() each time a check box is checked or unchecked
It also colors the background based on whether the checkbox is checked or not.
<script type="text/javascript"> //<![CDATA[
var div=0;
var c = new Array;
var d = new Array;
toggle = new Array;
toggle[true] = 'checked="checked"';
toggle[false] = '';
bg = new Array;
bg[true] = '#f00';
bg[false] = '#2985EA';
function chk(id){
d[id].style.backgroundColor=bg[c[id].checked];
}
function init(){
var checked,did;
var divs = document.getElementsByTagName("div");
for (div=0; div<divs.length; div++){
did = divs[div].getAttribute("id");
if (did != null){
if (did.substring(0,1) == "d"){
var i = did.substring(1,3);
c[i] = document.getElementById('c' + i);
d[i] = document.getElementById('d' + i);
checked = c[i].checked;
d[i].style.backgroundColor=bg[checked];
}
}
}
}
window.onload = init;
//]]>
</script>
Then when the form is submitted for confirmation you can check the selected check boxes by adding $checked to each checkbox
<td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\" $checked[$ndx0] />$row[0]</div></td>
Then add $checked["$val"] = 'checked="checked"'; to the $_POST loop
$checked = array();
$sub = intval($_POST['sub'];
if($sub == 1){
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
$checked["$val"] = 'checked="checked"';
}
}
}

change div containing checkbox attributes when checked

this is my javascript that allows for a filter search field ...
function escape4regex(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function searchRegExFieldKeyUp()
{
var table = document.getElementById('ModelFilter');
var cells = table.getElementsByTagName('div');
var searchterms = escape4regex(this.value);
var regVar = '(?=.*' + searchterms.replace(/\s/g, '.*)(?=.*') + '.*)';
var i=cells.length;
while (i--)
{
var cell = cells[i];
var rowStr = cell.innerHTML;
// remove all tags
rowStr = rowStr.replace(/<(?:.|\n)*?>/gm, '').replace(/\n|\s{2,}/gm, ' '); // searches whole row
var regex = new RegExp(regVar,"gi");
var result = (regex.test(rowStr));
if(result)
{
cell.style.display = "";// check if compat with IE
}
else
{
cell.style.display = "none";
}
}
}
this creates checkboxes from databse inputs
<div id="ModelFilter">
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo"<div class=\"modelfilter_td\" id=\"modelfilter_td\">";
echo"<input type=\"checkbox\" id = \"$row[ModelID]\"
name = \"selectedModels[]\"value =\"$row[Model]\" onclick=\"chkcontrol.apply(this);\">";
echo "$row[Model]";
echo"</div>";
}
echo"</div>";
I want to do the following :
when the checkbox is checked, it stays visible, even if it is not in the search terms of the filter field.
when the checkbox is checked , the background color is changed.
the checkbox and the title for the checkbox is held within a div, I want to allow the user to click anywhere in the div to allow toggling of the checkbox.
Anyone start me ont the right track with this?
EDIT: here is a solution to problem "3."
<script language="javascript">
$(document).ready(function(){
$(".modelfilter_td").click(function(e){
var chk = $($(this).find("input[type='checkbox']"));
if(chk.attr('checked'))
{
chk.attr('checked',false);
}else{
chk.attr('checked',true);
}
});
});
This is not a solution for you problem, but a recommendation on php-usage in html context:
<div id="ModelFilter">
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<div class="modelfilter_td" id="modelfilter_td">
<input
type="checkbox"
id="<?php echo $row['ModelID'] ?>"
name="selectedModels[]"
value="<?php echo $row['Model'] ?>"
onclick="chkcontrol.apply(this);"
>
<?php echo $row['Model'] ?>
</div>
<?php endwhile ?>
</div>
This enables most IDEs to deal with HTML-autocompletion and code-analysis.

Javascript Popup Windows

I have a popup window code that I have used before in login forms. The code displays an in-page popup.
This is the code:
<?php
//In Page Popup Box with Faded Background by Jerry Low #crankberryblog.com
//Find other useful scripts at the Crankberry Blog
//SETTINGS
$fade_amount = 60; //In Percentage
$box_width = 400;
$box_background = 'FFFFFF'; //Hex Color
$box_border_width = 2;
$box_border_color = '999999'; //Hex Color
$close_box = 1; //Do You Want The Close Bar on Top 1 = Yes, 0 = No
$extension = ""; // Other Variables that maybe needed, page number etc.
//Begin Popup Box
$left_margin = ( 0 - ($box_width*0.5) );
$page_url = basename($_SERVER['PHP_SELF']);
if ($extension!="") $page_url .= '?' . $extension;
if (isset($_GET['popup'])) {
echo '<div class="popup" style="width:'.$box_width.'px; background: #'.$box_background.'; margin-left:'.$left_margin.'px;';
if ($box_border_width>1) echo ' border: '.$box_border_width.'px solid #'.$box_border_color.';';
echo '">';
//Close Box
if ($close_box===1) echo '<div class="popup_close">Close (x)</div>';
?>
<!–- START YOUR POPUP CONTENT HERE -–>
Popup content goes in here!
<!–- END OF YOUR POPUP CONTENT HERE -–>
<?php
echo '</div>
<div class="fade" onclick="location.replace(\''.$page_url.'\');" style="opacity: 0.'.$fade_amount.'; -moz-opacity: 0.'.$fade_amount.';filter: alpha(opacity: '.$fade_amount.');"></div>
<div class="fade_container">';
}
?>
Activated Box
This code contains a link that reloads the page with parameters/arguments to show the popup.
I want to update this code to make the popup appear/hide without
This is what I have done so far, yet the popup doesn`t show.
Now I want to update the code to work as follows.
<link rel=StyleSheet href="css/popup.css" type="text/css" media=screen></link>
<?php
//In Page Popup Box with Faded Background by Jerry Low #crankberryblog.com
//Find other useful scripts at the Crankberry Blog
//SETTINGS
$fade_amount = 60; //In Percentage
$box_width = 400;
$box_background = 'FFFFFF'; //Hex Color
$box_border_width = 2;
$box_border_color = '999999'; //Hex Color
$close_box = 1; //Do You Want The Close Bar on Top 1 = Yes, 0 = No
$extension = ""; // Other Variables that maybe needed, page number etc.
//Begin Popup Box
$left_margin = ( 0 - ($box_width*0.5) );
$page_url = basename($_SERVER['PHP_SELF']);
if ($extension!="") $page_url .= '?' . $extension;
{
echo '<div id="pop_up" class="popup" style="visibility:hidden; width:'.$box_width.'px; background: #'.$box_background.'; margin-left:'.$left_margin.'px;';
if ($box_border_width>1) echo ' border: '.$box_border_width.'px solid #'.$box_border_color.';';
echo '">';
//Close Box
if ($close_box===1) echo '<div class="popup_close"><a href="#" ChangeStatus()>Close (x)</a></div>';
?>
<!–- START YOUR POPUP CONTENT HERE -–>
Popup content goes in here!
<!–- END OF YOUR POPUP CONTENT HERE -–>
<?php
echo '</div>
<div id="fade_div" class="fade" onclick="location.replace(\''.$page_url.'\');" style="visibility:hidden; opacity: 0.'.$fade_amount.'; -moz-opacity: 0.'.$fade_amount.';filter: alpha(opacity: '.$fade_amount.');"></div>
<div class="fade_container">';
}
?>
Activated Box
<script>
function ChangeStatus()
{
div = document.getElementById('fade_div').style.visibility;
popup = document.getElementById('pop_up').style.visibility;
alert(popup);
if(popup == "hidden")
{
div = "visible";
popup = "visible";
}
else
{
div = "hidden";
popup = "hidden";
}
}
</script>
ignore the CSS files as it is working fine.
I guess the problem is with the JS. Can anyone help me?
change your javascript to this:
if(popup == "hidden")
{
document.getElementById('fade_div').style.visibility = "visible";
document.getElementById('pop_up').style.visibility = "visible";
}
and
else
{
document.getElementById('fade_div').style.visibility = "hidden"
document.getElementById('pop_up').style.visibility = "hidden";
}

Categories