How to remove selected underline and line-through in the js tree? - javascript

I have a problem to remove the line-through in the js tree. For example now my tree nodes is 199 test Rujuk Kod:100-1-1. I have added the line-through in the 199 test Rujuk Kod:100-1-1. But I just want add in the 199 test, Rujuk Kod:100-1-1 don't want add line-through. Hope someone can help me solve this problem. Thanks.
Below is my coding:
<?php
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
$siri_pindaan = $row['siri_pindaan'];
$effective_date = $row['effective_date'];
$filing_code_refer = $row['filing_code_refer'];
$filing_code_link = $row['filing_code_link'];
if ($filing_code_refer != NULL) {
$refer_to_code = "Rujuk Kod:";
}
if ($filing_code_refer == NULL) {
$refer_to_code = " ";
}
if ($filing_code_link != NULL) {
$link_to_code = "Berhubung Kod:";
}
if ($filing_code_link == NULL) {
$link_to_code = " ";
}
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $row['name'] . ' ' ."<span id='open' style='font-size:9px;'>".$refer_to_code .$row['filing_code_refer']."</span>" .' '. "<span id='open' style='font-size:9px;'>".$link_to_code .$row['filing_code_link']."</span>" .' '. "<span id='open' style='font-size:9px;'>".$row['description_update']."</span>",
"category" => $row['category'],
"filing_code_refer" => $row['filing_code_refer'],
// "status" => $row['status'], // status 0 is inactive, status 1 is active
"data" => array("status" => $row['status'],"add_underline"=>$row['add_underline']) ,
"state" => array("selected" => $selected,"opened"=>$opened)
);
}
?>
<script>
var colorNodes = function(nodelist) {
var getStrike = function(status) {
if (status === "0") {
return "line-through";
} else {
return "";
}
};
var getUnderline = function(add_underline) {
if (add_underline === "1") {
return " underline;text-underline-position: under;";
} else {
return "";
}
};
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "color:" + getColor(parseInt(n.text.substr(0, 3), 10))+ ";"+"text-decoration:" + getStrike(n.data.status) + getUnderline(n.data.add_underline);
tree.redraw_node(n.id); //Redraw tree
colorNodes(n.children); //Update leaf nodes
});
};
</script>
This is my jsfiddle: https://jsfiddle.net/mLr5w2pd/1/
My expected result is like below the picture:
Updated
Below is show the content in the js tree.
<!-- Initialize jsTree -->
<div id="folder_jstree" title=""></div>
<!-- Store folder list in JSON format -->
<textarea style="" id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea>
Updated 2

add below css to make the span inside the jstree-anchor as inline-block, then it will not have 'line-through'
.jstree-anchor span {
display: inline-block;
}
check the fiddle https://jsfiddle.net/mL407ya1/
and if you notice you have line-through in last, that is because of space in below code line #2 (text)-
{
"id":"753","parent":"#",
"text":"199 test <span id='open' style='font-size:9px;'>Rujuk Kod:190-1-1<\/span> <span id='open' style='font-size:9px;'> <\/span> <span id='open' style='font-size:9px;'> <\/span>",
"category":"jtm",
"filing_code_refer":"190-1-1",
"data":{"status":"0","add_underline":"0"},
"state":{"selected":false,"opened":false}
}
if you can remove the space between <span> and </span> it will work as expected.
UPDATE
if you can't remove the spaces from source, in code you can remove the space using regex. while you are parsing string to json array, remove the extra space before parsing. try below
let txtVal = $('#txt_folderjsondata').val();
txtVal = txtVal.replace(/> </g, '><');
var folder_jsondata = JSON.parse(txtVal);
Try the below fiddle.
https://jsfiddle.net/mL407ya1/1/

Related

"Check All" checkbox shows ambiguous behaviour with pagination

thanks for being so supportive to the topics asked. I have a built a 'User Approval' system wherein the admin gets list of registered users and approves them by using checkboxes for each and 'Check all' that selects all users. Table has pagination of 10 users at once. My issue here is when I 'check all' on the second page with 10 users, the table automatically selects and displays the first 10 users also i.e. the first page with 10 users. How can I stop the page to second list only when "check all" is implemented on second list of 10 candidates. I am confused on where it has gone wrong and getting no clue . Any help or advice will be appreciated and helpful. Here is the code for javascript that I have used,
<script type="text/javascript">
var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items
//select all checkboxes
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item is unchecked
if(this.checked == false){
select_all.checked = false;
}
//check "select all" if all checkbox items are checked
if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
select_all.checked = true;
}
});
}
</script>
And the php+html for the table header "Check all"
<input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>"> </th>
And my pagination class,
<?php
class pagination
{
var $page = 1; // Current Page
var $perPage = 10; // Items on each page, defaulted to 10
var $showFirstAndLast = false; // if you would like the first and last page options.
function generate($array, $perPage = 10)
{
// Assign the items per page variable
if (!empty($perPage))
$this->perPage = $perPage;
// Assign the page variable
if (!empty($_GET['page'])) {
$this->page = $_GET['page']; // using the get method
} else {
$this->page = 1; // if we don't have a page number then assume we are on the first page
}
// Take the length of the array
$this->length = count($array);
// Get the number of pages
$this->pages = ceil($this->length / $this->perPage);
// Calculate the starting point
$this->start = ceil(($this->page - 1) * $this->perPage);
// Return the part of the array we have requested
return array_slice($array, $this->start, $this->perPage);
}
function links()
{
// Initiate the links array
$plinks = array();
$links = array();
$slinks = array();
// Concatenate the get variables to add to the page numbering string
if (count($_GET)) {
$queryURL = '';
foreach ($_GET as $key => $value) {
if ($key != 'page') {
$queryURL .= '&'.$key.'='.$value;
}
}
}
// If we have more then one pages
if (($this->pages) > 1)
{
// Assign the 'previous page' link into the array if we are not on the first page
if ($this->page != 1) {
if ($this->showFirstAndLast) {
$plinks[] = ' «« First ';
}
$plinks[] = ' « Prev ';
}
// Assign all the page numbers & links to the array
for ($j = 1; $j < ($this->pages + 1); $j++) {
if ($this->page == $j) {
$links[] = ' <a style="font-weight: bold;">'.$j.'</a> '; // If we are on the same page as the current item
} else {
$links[] = ' '.$j.' '; // add the link to the array
}
}
// Assign the 'next page' if we are not on the last page
if ($this->page < $this->pages) {
$slinks[] = ' Next » ';
if ($this->showFirstAndLast) {
$slinks[] = ' Last »» ';
}
}
// Push the array into a string using any some glue
return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
}
return;
}
}
?>

How to add an array from the data attribute and id using javascript and combine them in array php?

I just want to ask if how to merge this two array from all id value and data-rate value on my list order? there is too many ul li, so i need to get them all and store it into array.
this is my code in javascript:
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("ul.reorder-photos-list li").each(function() { x.push($(this).attr('data-rate').substr(9)); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {
ids: " " + h + "",
rate: " " + x + ""
},
success: function(html)
{
window.location.reload();
/*$("#reorder-helper").html( "Reorder Completed - Image reorder have been successfully completed. Please reload the page for testing the reorder." ).removeClass('light_box').addClass('notice notice_success');
$('.reorder_link').html('reorder photos');
$('.reorder_link').attr("id","");*/
}
});
and this is my html code:
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?= $row['rate']?>" data-rate="<?php echo $row['rate']; ?>" >
and then in my order_update.php this is my code.
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n], "data" => $rates[$n]);
$n++;
}
and this is my insert query from orderArray
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$update = mysqli_query($this->connect,"UPDATE `test` SET `order` = $count, `rate`=$array[rate] WHERE id = $array[id]");
$count ++;
}
return true;
}
hope someones helps me. :)thanks in advance!
When setting up your data, you don't need to have multiple loops. You can loop through the data once:
var dataArray = [];
$("ul.reorder-photos-list li").each(function() {
var el = $(this),
input = el.children(':input'); // This gets the input decendent of the li
// When adding one item at a time to an array, array[array.length] = item is better
dataArray[dataArray.length] = {
id: el.attr('id').substr(9),
rate: input.val(),
};
});
$.ajax({
type: "POST",
url: "order_update.php",
data: { items: dataArray }, // items gives the PHP something to use as a key in the POST data
success: function(html) {...}
});
Your PHP will look like this:
// The data passed from the Ajax call is already an array
$itemsArray = $_POST['items'];
// Your function to process the array
function updateOrder($orderArray) {
foreach ($orderArray as $index => $array) {
// $index will already have a count, you need to +1 because it's 0-based
mysqli_query($this->connect, "UPDATE `test` SET `order` = " . ($index + 1) . ", `rate`=" . $array['rate'] . " WHERE id = " . $array['id']);
}
return true;
}
var rates;
$("ul.reorder-photos-list li").each(function() {
rates.id.push($(this).attr('id').substr(9));
rates.rate.push($(this).attr('data-rate').substr(9));
});
This will create your JSON object of h/x pairs.
$.ajax({
type: "POST"
, url: "order_update.php"
, data: { JSON.stringify(rates); }
, success: function(html) {
window.location.reload();
/* $("#reorder-helper").html(
* "Reorder Completed - Image reorder have been successfully completed.
* Please reload the page for testing the reorder."
* ).removeClass('light_box').addClass('notice notice_success');
* $('.reorder_link').html('reorder photos');
* $('.reorder_link').attr("id","");
*/
}
});
This should fix your call to send the correct data.
Your PHP side is going to want to have something similar to this:
if(isset($_POST['rates'])) {
$ratesString = $_POST['rates'];
$rates = json_decode($ratesString);
}
// Do other things with $hx`
Your insert query is off, too. You need to declare each value as a variable or your compiler is going to hate your PHP, too. You also have some unnecessary quotes in your query.
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$rate = $array['rate'];
$id = $array['id'];
mysqli_query($this->connect,"UPDATE test SET order = $count, rate = '$rate' WHERE id = '$id'");
$count ++;
}
return true;
}
For your HTML, I think this is what you were going for, but not sure since it's not really explained all that well...Feel free to comment on your intentions.
<ul>
<?php foreach($orderArray as $array) : ?>
<li id="image_li_<?php echo $array['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?php echo $array['rate']?>" data-rate="<?php echo $array['rate']; ?>" ></li>
<?php endforeach; ?>
</ul>
Hope this helps.
-C§
I got the code now. thanks for your help guys!
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("input").each(function() { x.push($(this).val()); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {ids: " " + h + "",rate: " " + x + ""},
/*data: { items: dataArray },*/
success: function(html)
{
...
}
});
In Php side:
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n] , "rate" => $rates[$n]);
$n++;
}
$db->updateOrder($orderArray);
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
mysqli_query($this->connect, "UPDATE `test` SET `morder` = " . $count . ", `mtoursrate`=" . $array['rate'] . " WHERE id = " . $array['id']);
$count ++;
}
return true;
}

Submenu keep active when user click on it and open in a new page

I have problem when a visitor clicks on a submenu and the link opens in a new page, so I want to keep that submenu active on that page.
I have css class active and javascript for opening it, what I need is to make it with php to be active.
This is UL with class:
This is my code. Can it be done with php or with javascript.
<ul>
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?=$emrikategorise;?>
<ul>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");
$rPrind = mysqli_query($dbc,$qPrind);
while($prind = mysqli_fetch_array($rPrind)) {
?>
<li><?=$prind['kemri']?> </li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php }
mysqli_free_result($rKategori);
}
?>
</ul>
You can see menu on the left in The website is www.sitimobil.mk
You probably will need to build the array before outputting to be able to determine which menus should be active. You can also combine it with an optimization of the query to not have to do 1 query per category.
Something like:
$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$id = $exKat['kid'];
//To prevent numerical array with unused space
$name = 'kategori'.$exKat['kid'];
$list[$name] = $exKat;
//Calculate depth to see if the menu is a sub..sub..sub menu etc.
$parent = $list[$name]['kprind'];
if($parent == 0) {
$list[$name]['depth'] = 0;
$list[$name]['childCount'] = 0;
}
else {
$list['kategori'.$parent]['childCount']++;
$list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
}
if($id == $active) {
$list[$name]['active'] = true;
while($parent != 0) {
$parentName = 'kategori'.$parent;
$list[$parentName]['active'] = true;
$parent = $list[$parentName]['kprind'];
}
}
else
$list[$name]['active'] = false;
}
mysqli_free_result($rPrind);
//Once we have that we can output the results...
function output_menu($list, $parent = 0, $active = false)
$activeClass = $active ? ' class="active"' : '';
echo '<ul'.$activeClass.'>';
foreach($list as $row){
if($row['kprind'] != $parent) continue;
$link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
echo '<li>'.$row['kemri'].'';
if($row['childCount'] > 0)
output_menu($list, $row['kprind'], $row['active']);
echo '</li>';
}
echo '</ul>';
}
output_menu($list);
}
This is still a bit rough but should do the trick. It can probably be optimized so that we don't have to go through the list too many times but has the benefit of not having to request too many calls to the database. That should result in a lighter workload for the DB and faster output.

Javascript not running when triggered by javascript

I have an html form in with a drop down menu and a series of checkboxes. The dropdown has two options. Each option is supposed to check several of the checkboxes using javascript with an onchange event within the "select" tag. This works 100%, but it fails when I trigger it with more javascript.
I have narrowed it down to the part where is resets all the checkboxes to be unchecked. It is then supposed to select the boxes it needs based on the drop down, but because it fails to uncheck them all, they all remain checked.
Here is the code:
select box:
<select name='myrp_autogroups' id='myrp_autogroups' onchange='myrp_group_selector();'>
<option></option>
<?php
$presets = get_option("myrp_presets");
for ($i = 0; $i < count($presets); $i++) {
$preset = $presets[$i];
echo "<option value='";
for ($b = 0; $b < count($preset[1]); $b++) {
$checkbox = $preset[1][$b];
echo $checkbox . ",";
}
echo "'";
echo ">" . $preset[0] . "</option>";
}
update_option("myrp_presets", $presets);
?>
</select>
<input type="button" value="change" onclick="change_group();">
<script type='text/javascript'>
window.onload = change_group();
</script>
Javascript:
function myrp_group_selector()
{
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=false;
document.getElementById("myrp_average_value_top").value="";
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_value_bottom").value="";
document.getElementById("myrp_average_bottom").checked=false;
}
var checkThese = document.getElementById("myrp_autogroups")[document.getElementById("myrp_autogroups").selectedIndex].value;
var checkArray = checkThese.split(",");
var average = "avg";
// check the new stuff
for(var i in checkArray)
{
if(checkArray[i] == average)
{
if(document.getElementById("myrp_average_top") != null)
{
document.getElementById("myrp_average_top").checked=true;
}
if(document.getElementById("myrp_average_bottom") != null)
{
document.getElementById("myrp_average_bottom").checked=true;
}
}
else
{
document.getElementById("myrp_c_"+checkArray[i]).checked=true;
document.getElementById("myrp_value_"+checkArray[i]).disabled=false;
}
}
}
function change_group() {
select = document.getElementById('myrp_autogroups');
if(select.value != '2,3,4,5,6,'){
select.value = '2,3,4,5,6,';
select.onchange();
}
}
I have narrowed it down to this section, keep in mind it functions perfectly if i manually select an option from the dropdown and doesn't work when triggered by java:
// reset everything.
$mrjQ(".myrp_checkboxes").each(function() {
var name = this.id.split("myrp_c_");
if(name.length == 2) {
document.getElementById("myrp_value_" + name[1]).disabled=true;
document.getElementById("myrp_value_" + name[1]).value="";
this.checked=false;
}
});
the wrong is :
window.onload = change_group() ;
it should be
window.onload = change_group;

Magento Images switcher for custom options

I have created a custom options image switcher for Magento, script compares value from options in drop-down with all image names related to product, and finds the most similar one, you can see an example here
The problem is how to add the "selected" option image to the cart, or better to say how to apply that image instead of the default thumbnail in the cart?
anyway here is the complete code - maybe someone can even find this part useful :)
<?php
// load all images related to product
$product = $this->getProduct();
$galleryData = $product->getData('media_gallery');
$images_array = array();
foreach ($galleryData['images'] as $image) {
array_push($images_array, $image['file']);
}?>
<?php
$colour_select_id = '';
$custom_options_arr = array();
foreach ($_options as $_option) {
if ($_option->getTitle() == 'Helmet Color/Design' || $_option->getTitle() == 'Color') {
$colour_select_id = 'select_' . $_option->getId();
$values = $_option->getValues();
foreach ($values as $value) {
$current_option = ($value->getData());
$custom_options_arr[$current_option['option_type_id']] = $current_option['title'];
}
}
}
// $custom_options_arr now holds key=>value pairs of option_type_id => title
$custom_images_to_output = array();
foreach ($custom_options_arr as $key => $value) {
$best_match = $images_array[0];
for ($i = 1; $i < count($images_array); $i++) {
if (similar_text(strtoupper($images_array[$i]), strtoupper($value)) > similar_text(strtoupper($best_match), strtoupper($value))) {
$best_match = $images_array[$i];
}
}
$custom_images_to_output[$key] = $best_match;
}
$base_url = Mage::getBaseUrl('media') . 'catalog/product';
?>
<?php if ($colour_select_id) { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
var opt_object = <?php echo json_encode($custom_images_to_output); ?>;
var base_path = '<?= $base_url;?>';
jQuery("#<?= $colour_select_id ?>").change(function() {
var optionValue = jQuery(this).attr('value');
if (optionValue) {
var optionValueText = jQuery.trim(jQuery('#<?= $colour_select_id ?> :selected').text());
if (opt_object.hasOwnProperty(optionValue)) {
optionValueText = opt_object[optionValue];
}
jQuery("#image").fadeOut(function() {
jQuery(this).load(function() {
jQuery(this).fadeIn(); });
jQuery(this).attr("src", base_path + optionValueText);
jQuery('#image-zoom').attr("href", base_path + optionValueText);
});
}
});
});
</script>

Categories

Resources