How to add class dynamically using javascript - javascript

I want to add an class to an closest element of an click object.
If you see code below, I would like to add an class to .process-signs-direction-cover-button
There is an loop, so the above classes get's repeated. But I want to add an classes to closest() .process-signs-direction-cover-button of where I click.
See picture
MY php:
<div class="col-md-6 reduced_padding_col7">
<?php
$signs_to_direction_and_cover_process = $mysqli_scs->query("SELECT * FROM agsigns_db3.stock_stk where idstc_stk = ".$row['idstc_stk']." AND directioncolor_stk = 'Yellow' ");
$row_cnt = $signs_to_direction_and_cover_process->num_rows;
if($row_cnt > 0){
while ($row = mysqli_fetch_assoc($signs_to_direction_and_cover_process)) { ?>
<div class="col-md-4 thumbnail"><img src="../../css/sign-directions/<?php echo $row['directionimage_stk']; ?>" class="processing-signs-direction-cover-sign-direction-selection-process" id="<?php echo $row['id_stk']; ?>" />
<div class="col-xs-12 text-center signs-text">
<span class="current_stock_figure">
<?php echo $row['stock_stk'] == "" ? "N/A" : $row['stock_stk']; ?>
</span>
<span class="max_stock_figure">
<?php echo $row['maxlevel_stk']; ?>
</span>
</div>
</div>
<?php
}
}
?>
</div>
<div class="col-md-2 process-button">
<img src="../../css/buttons/process-signs-covered-disabled.png" id="" class="process-signs-direction-cover-button disabled_button" rel="<?php echo $row['signcode_sgn']; ?>" alt="covered"/>
<div class="options-remember-checkbox">
<input type="checkbox" class="rememberoptions" name="rememberoption" value="checked" > Remember Options<br>
</div>
MY JQuery
$(".processing-signs-direction-cover-sign-direction-selection-process").click(function() {
$(this).closest("process-button.process-signs-direction-cover-button").toggleClass("process");
});
Modify
Question Modified
Image code

In your jquery part use addClass instead of toggleClass .
$(".processing-signs-direction-cover-sign-direction-selection-process").click(function() {
$(this).closest("process-button.process-signs-direction-cover-button").addClass("process");
});

Related

Loop through <li> using javascript/jquery

Note: This is a mixture of Php, Javascript and html.
I have a code below
<div class="chat-sidebar-list-wrapper pt-2">
<h6 class="px-2 pt-2 pb-25 mb-0">MAIDS</h6>
<ul class="chat-sidebar-list maid-list-wrapper">
<?php
foreach($all_maids as $all_maid){
?>
<!-- displaying looped results in <li> using php foreach method-->
<li id="<?php echo $all_maid->id?>" class="bingo">
<input type="hidden" id="hidden_receiver_id" name="hidden_receiver_id" value="<?php echo $all_maid->id?>"/>
<div class="d-flex align-items-center">
<div class="avatar m-0 mr-50"><img src="<?php echo base_url('uploads/'); ?>images/<?php echo get_user_image($all_maid->id)?>" height="36" width="36" alt="sidebar user image">
<span class="avatar-status-busy"></span>
</div>
<div class="chat-sidebar-name">
<h6 class="mb-0 maid-names"><?php echo $all_maid->first_name. "" . $all_maid->last_name ?></h6><span class="text-muted">Maid</span>
</div>
</div>
</li>
<?php } ?>
</ul>
.......
</div>
What i want is, when you click on each <li> items, you should be able to get the ID from the input tag <input type="hidden" id="hidden_receiver_id" name="hidden_receiver_id" value="<?php echo $all_maid->id?>"/>.
So how can i loop the <li> items and get each of it IDs from the input tag?
I tried something below but not working
var listItems = $(".maid-list-wrapper li");
listItems.each(function(idx, li) {
//var id = $(li).text();
alert($("li.bingo").find("input#hidden_receiver_id").text());
});
Using jQuery
var items = $(".chat-sidebar-list li");
items.each(function(id, li) {
var OneItem = $(li);
// and the rest of your code.OneItem is an object here
});
The answer is
i added class="hidden_receiver_id" to <input type="hidden" id="hidden_receiver_id" class="hidden_receiver_id" name="hidden_receiver_id" value="<?php echo $all_maid->id?>"/>
$('.maid-list-wrapper li').click(function() {
//name of each user
console.log($(this).find("h6.maid-names").text());
//ID of each user
//alert($(this).find("input[type='hidden']").val());
console.log($(this).find("input.hidden_receiver_id").val())
});

unable to display div even if condition is true, always displaying else part in php

I am trying to show div on tab click only if condition is true, but always i am getting else div which is displayed in else part even when if condition is true
$('#err').removeClass('uk-active');
$('#MA_st').addClass('uk-active');
i have tried above code on success ajax call and also tried the following on tab click
$("#tab_list").on('click','li',function (){
$('#err').removeClass('uk-active');
$('#MA_st').addClass('uk-active');
});
here is my php code to show div in view file
<?php
$state_val = "";
if(isset($_GET['state_val'])){
$state_val = $_GET['state_val'];
print_r($state_val);
}
if($data['state'] == 'MA' || $state_val == 'MA'){?>
<div id="MA_st">
<li>
<div class="uk-form-row">
<label class="uk-form-label"><?php echo Yii::t("default","Number")?></label>
<?php echo CHtml::textField('txt_number',
isset($data['number'])?$data['number']:""
,array(
'class'=>'uk-form-width-large'
))?>
</div>
<div class="uk-form-row">
<label class="uk-form-label"><?php echo Yii::t("default","Name")?></label>
<?php echo CHtml::textField('txt_name',
isset($data['name'])?$data['name']:""
//"ABC"
,array(
'class'=>'uk-form-width-large',
'autocomplete'=>"off"
))?>
</div>
</li>
</div>
<?php }else{?>
<div id="err">
<p>Inforamtion is not avaialble</p>
</div>
In either case of "If" or "Else" the second div is not being rendered, JS needs both divs to be rendered properly, try something like
<?php
$state_val = "";
if(isset($_GET['state_val'])){
$state_val = $_GET['state_val'];
print_r($state_val);
}
if($data['state'] == 'MA' || $state_val == 'MA'){?>
<div id="MA_st" class="uk-active">
<li>
<div class="uk-form-row">
<label class="uk-form-label"><?php echo Yii::t("default","Number")?></label>
<?php echo CHtml::textField('txt_number',
isset($data['number'])?$data['number']:""
,array(
'class'=>'uk-form-width-large'
))?>
</div>
<div class="uk-form-row">
<label class="uk-form-label"><?php echo Yii::t("default","Name")?></label>
<?php echo CHtml::textField('txt_name',
isset($data['name'])?$data['name']:""
//"ABC"
,array(
'class'=>'uk-form-width-large',
'autocomplete'=>"off"
))?>
</div>
</li>
</div>
<div id="err">
<p>Inforamtion is not avaialble</p>
<?php }else{?>
<div id="MA_st">
<li>
<div class="uk-form-row">
<label class="uk-form-label"><?php echo Yii::t("default","Number")?></label>
<?php echo CHtml::textField('txt_number',
isset($data['number'])?$data['number']:""
,array(
'class'=>'uk-form-width-large'
))?>
</div>
<div class="uk-form-row">
<label class="uk-form-label"><?php echo Yii::t("default","Name")?></label>
<?php echo CHtml::textField('txt_name',
isset($data['name'])?$data['name']:""
//"ABC"
,array(
'class'=>'uk-form-width-large',
'autocomplete'=>"off"
))?>
</div>
</li>
</div>
<div id="err" class="uk-active">
<p>Inforamtion is not avaialble</p>
</div>
}?>

Unset a single item form a php array embedded in a html site with JS button

My question is. I want to press that remove button at the end and remove my item form the session.
how can i do this?
js:
$('.remove button') .click (function() {
removeItem(This);
});
PHP and HTML:
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
print("<div class=\"basket-product\">
<div class=\"item\">
<div class=\"product-image\">
<img src=\"http://placehold.it/120x166\" alt=\"Placholder Image 2\" class=\"product-frame\">
</div>
<div class=\"product-details\">
<h1><strong><span class=\"item-quantity\">1</span> x ".$data["StockItemName"]."</strong></h1>
<p><strong>".$color." ".$size."</strong></p>
<p>Product Code - ".$data["StockItemID"]."</p>
</div>
</div>
<div class=\"price\">".$data["RecommendedRetailPrice"]."</div>
<div class=\"quantity\">
<input type=\"number\" value=\"1\" min=\"1\" class=\"quantity-field\">
</div>
<div class=\"subtotal\">". $data["RecommendedRetailPrice"] * 1 ."</div>
<div class=\"remove\">
<button>Remove</button>
</div>
</div>");
}
I tried using Unset in allot of places, but that doesn't seem to get working :')
:)
The solution is rather easy, but requires some explanation in order to be understood.
What you need here is to:
Create a new php file, which would fetch the post data (in this case ID of an element) and then simply unset the key (sub-array), which contains the cart item you want to remove.
You can use $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID')); and then simply unset it unset($_SESSION["cart"][$key_to_remove]);
Assign id="remove_<?php echo $data["StockItemID"]; ?>" to the <div class="basket-product"> and data-product-id="<?php echo $data["StockItemID"]; ?>" to the button, so you can identify it for item removal via javascript/jquery and you need that value extracted later for the item you want to remove from the corresponding session array (which is, in this case, $_SESSION["cart"]).
Create a callback function for removal on('click', function(){});
Inside that function extract that value data-product-id from the button you just clicked var stock_item_id=$(this).attr('data-product-id');
Inside the same function, after step 4, create an ajax call to the file from step 1 with the post data from step 4
On successful execution of an ajax call, delete the corresponding product row you have marked with id="remove_<?php echo $data["StockItemID"]; ?>" in step 2 with the following code $("#remove_"+stock_item_id).remove();
In the end, your code would look like this
YOUR INITIAL PHP AND HTML (With small corrections)
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
?>
<div class="basket-product">
<div class="item">
<div class="product-image">
<img src="http://placehold.it/120x166" alt="Placholder Image 2" class="product-frame">
</div>
<div class="product-details">
<h1>
<strong>
<span class="item-quantity">
1
</span>
x <?php echo $data["StockItemName"]; ?>
</strong>
</h1>
<p>
<strong>
<?php echo $color." ".$size; ?>
</strong>
</p>
<p>
Product Code - <?php echo $data["StockItemID"]; ?>
</p>
</div>
</div>
<div class="price">
<?php echo $data["RecommendedRetailPrice"]; ?>
</div>
<div class="quantity">
<input type="number" value="1" min="1" class="quantity-field">
</div>
<div class="subtotal">
<?php echo $data["RecommendedRetailPrice"]; ?> * 1
</div>
<div class="remove">
<button data-product-id="<?php echo $data["StockItemID"]; ?>">
Remove
</button>
</div>
</div>
<?php
}
?>
JS
$(document).ready(function(){
$('.remove button').on('click', function() {
var stock_item_id=$(this).attr('data-product-id');
$.ajax({
url: "new_php_file_created_to_remove_item_from_session_via_ajax.php",
data:
{stock_item_id : stock_item_id}
}).done(function() {
$("#remove_"+stock_item_id).remove();
});
});
});
NEW PHP FILE (new_php_file_created_to_remove_item_from_session_via_ajax.php)
<?php
$stock_item_id = $_POST['stock_item_id'];
$key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID'));
unset($_SESSION["cart"][$key_to_remove]);
if(isset($_SESSION["cart"][$key_to_remove])) {
return false;
}
return true;
For the sake of readability and further maintenance and possible additions, I would strongly recommend you to separate php, html and js code into separate files, but that's only a suggestion. :)

Hide/Show toggle echo results in php

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>
please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"
<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working
Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

I'm trying to get the id when clicking different messages from sql database

I'm trying to get the id when I click different messages.
This is my javascript:
$(document).ready(function() {
$('#message-subject-result').click(function(){
var message = document.getElementById('message_id').value;
alert(message);
});
});
I am pulling it from a php function that is:
<div id="message-subject-result">
<div id="message-date">'.$date.'</div>
<input type="hidden" id="message_id" value="'.$row['mes_id'].'"><div id="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div id="message-subject">SUBJECT: '.$row['subject'].'</div>
<div id="message-preview">'.$row['message'].'</div>
</div>
The javascript works but only when I click on the first echoed result. What am I doing wrong?
Replace duplicating ids with classnames and use find method:
$('.message-subject-result').click(function() {
var messageId = $(this).find('.message_id').val();
alert(messageId);
});
valid HTML should be:
<div class="message-subject-result">
<div clas="message-date">'.$date.'</div>
<input type="hidden" class="message_id" value="'.$row['mes_id'].'">
<div class="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div class="message-subject">SUBJECT: '.$row['subject'].'</div>
<div class="message-preview">'.$row['message'].'</div>
</div>
You must have all unique ids. Something like this will give you unique id's:
<?php
$i = 0;
foreach($result as $row) { ?>
<div id="message-subject-result">
<div id="message-date">'.$date.'</div>
<input type="hidden" id="message_id<?php echo $i; ?>" value="'.$row['mes_id'].'"><div id="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div id="message-subject">SUBJECT: '.$row['subject'].'</div>
<div id="message-preview">'.$row['message'].'</div>
</div>
<?php $i++;
} ?>

Categories

Resources