Unable to Filter Items in JavaScript - javascript

So, I'm trying to create a filter for this list of stores, so only the ones with content that is equal to the value of the input box will display. Unfortunately, my filter does not work correctly. For one, whatever I type in the input box causes all of my store elements to add the 'display' class, which causes my items to receive the style 'display: none;'. Secondly, it's not updating every time a key is pressed.
HTML:
<li class="p-3 clearfix store display">
<div class='float-left w-50'>
<div class='mb-1'><strong>Store Number:</strong><span class="store-info">
<?php
if (strlen($row['store_num']) < 4) {
if (strlen($row['store_num']) == 3) {
echo '0' . $row['store_num'];
} else if (strlen($row['store_num']) == 2) {
echo '00' . $row['store_num'];
}
} else {
echo $row['store_num'];
}
?>
</span></div>
<div class='mb-1'><strong>Store Name: </strong><span class='store-info'><?php echo $row['store_name']; ?></span></div>
<div class='clearfix mb-1'>
<p class='float-left'><strong>Address: </strong></p>
<span class='d-block store-info float-left'><?php echo $row['store_street']; ?></span>
<br>
<span class='d-block store-info float-left'><?php echo $row['store_city']; ?>, <?php echo strtoupper($row['store_state']); ?> <?php echo $row['store_zip']; ?></span>
</div> <!-- mb-1 -->
</div> <!-- float-left -->
<div class="float-left w-50 clearfix">
<div class="d-inline float-right">
<div class='mb-1'>
<strong>Time Zone: </strong><span class='time-zone store-info'><?php echo strtoupper($row['time_zone']); ?></span>
</div>
<div class='mb-1'>
<strong>Current Time: </strong><time>3:45pm</time>
</div>
<div class='mb-1'>
<strong>Phone Number:</strong><span class='store-info'>
<?php
$phone = $row['store_phone'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
<div class='mb-1'>
<strong>Fax Number:</strong><span class='store-info'>
<?php
$phone = $row['store_fax'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
</div> <!-- d-inline -->
</div> <!-- float-right -->
</li> <!-- clearfix -->
JavaScript:
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
for(var i = 0; i < spans.length; i++) {
if (spans[i].innerText.toLowerCase() != data) {
store.classList.remove('display');
} else {
store.classList.add('display');
}
}
});
});

If I understand your question correctly, you could make the following changes to your javascript to resolve the issues you're facing. Please see comments in code for explaination of what's going on:
search.addEventListener('keyup', function (e) {
var query = e.target.value.toLowerCase();
if (search.value.length >= 0) {
search.classList.add('focused');
label.classList.add('focused');
} else {
search.classList.remove('focused');
label.classList.remove('focused');
}
// recommend performing this query in the keyup event to ensure
// that you're working with the most up to date state of the DOM
var stores = document.querySelectorAll(".store");
stores.forEach(function(store) {
// query .store-info from current store
var spans = store.querySelectorAll(".store-info");
// hide the store by default
store.style.display = 'none';
for (var i = 0; i < spans.length; i++) {
var storeInfoText = spans[i].innerText.toLowerCase();
// consider revising search logic like so
if (storeInfoText.indexOf(query) !== -1 || !query) {
// display the store if some match was found
store.style.display = 'block';
}
}
});
});
Link to working jsFiddle here

I think your issue with it showing everything is because of the add remove... if a store already has display it will re add it and then only remove it once where as if it doesn’t you will get an error so try toggle
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
spans.filter(span=>{
if(span.innerText.toLowerCase().includes(data)){
store.classList.toggle('display');
}else{store.classList.toggle('display')
})
});

Related

Changing decimal prices Javascript

Im making a sweetshop project for my apprenticeship and ive done some test runs and have got all my code working but then i get my brief and the prices are changed depending on the weight and have got decimal prices instead of whole E.G £0.0.1 i thought this wouldnt make a difference but im not sure whats stopping the plus and minus button from changing the decimal price.
<?php
foreach ($result as $key => $value) { ?>
<div class="col-md-4 inner-container">
<div class="card border">
<div class="column-image" style=" background-image: url(<?php echo ($value['image']); ?>" >
</div>
<h2><?= $value['sweet_name'] ;?></h2><br/>
<p>Price: £<?= $value['price'] ; ?></p>
<p>Weight: <?= $value['weight'] ; ?>g</p>
£<span id="prices"><?php echo ( $value['price'] ); ?></span><br/>
<span id="weight"><?php echo ( $value['weight'] ); ?></span> g<br/>
<button onclick="minus()"> - </button><span id="quantity"> 1 </span><button onclick="plus()"> + </button><br/>
<!-- runs the function addcookie in javascript and passes paramater id -->
<button class="column-button" onclick="addcookie(<?php echo $value['id']; ?>)">Add to basket</button>
</div>
<?php } ?>
<script>
// these varibles are to not get [object HTMLSpanElement]
var weight = <?php echo ( $value['weight'] ); ?>;
var price = <?php echo $value['price']; ?>;
function addcookie(id){
// element can be anything in HTML
// innerHTML gets anything inside the html tags E.G quantity = 1
var quantity = document.getElementById('quantity').innerHTML;
var id = <?php echo $value['id']; ?>;
// creates the cookie with a key and a value and also creates a path to be stored
// this means i can access it on any page E.G basket.php
document.cookie = "zzz_"+id+"_id="+id+"; ;path=/";
document.cookie = "zzz_"+id+"_quantity="+quantity+"; ;path=/";
document.cookie = "zzz_"+id+"_weight="+weight+"; ;path=/";
}
function plus(){
// parseint changes strings into intergers
document.getElementById('quantity').innerHTML = parseInt( document.getElementById('quantity').innerHTML) +1;
document.getElementById('prices').innerHTML = parseInt( document.getElementById('prices').innerHTML) +price;
document.getElementById('weight').innerHTML = parseInt( document.getElementById('weight').innerHTML) +weight;
}
function minus(){
if (document.getElementById('quantity').innerHTML > 1){
document.getElementById('quantity').innerHTML = parseInt( document.getElementById('quantity').innerHTML) -1;
document.getElementById('prices').innerHTML = parseInt( document.getElementById('prices').innerHTML) -price;
document.getElementById('weight').innerHTML = parseInt( document.getElementById('weight').innerHTML) -weight;
}
}
</script>
i'm just wondering what i'm doing wrong? i've tried changing my parseInt to a ParseDouble but there was no change at all.
You're nearly there. parseFloat is what you need. There's no such function as ParseDouble or parseDouble, so that was probably producing errors in your browser's Console (you didn't say whether you'd checked for those or not).
I've also added some calls to .toFixed so you don't end up with large trailing decimal places, but you can adjust that according to the level of accuracy / rounding you need.
Live demo:
var weight = 5.2;
var price = 3.5;
function addcookie(id)
{
// element can be anything in HTML
// innerHTML gets anything inside the html tags E.G quantity = 1
var quantity = document.getElementById('quantity').innerHTML;
var id = 22;
// creates the cookie with a key and a value and also creates a path to be stored
// this means i can access it on any page E.G basket.php
//document.cookie = "zzz_" + id + "_id=" + id + "; ;path=/";
//document.cookie = "zzz_" + id + "_quantity=" + quantity + "; ;path=/";
//document.cookie = "zzz_" + id + "_weight=" + weight + "; ;path=/";
}
function plus()
{
document.getElementById('quantity').innerHTML = parseInt(document.getElementById('quantity').innerHTML) + 1;
document.getElementById('prices').innerHTML = (parseFloat(document.getElementById('prices').innerHTML) + price).toFixed(2);
document.getElementById('weight').innerHTML = (parseFloat(document.getElementById('weight').innerHTML) + weight).toFixed(2);
}
function minus()
{
if (parseInt(document.getElementById('quantity').innerHTML) > 1) {
document.getElementById('quantity').innerHTML = parseInt(document.getElementById('quantity').innerHTML) - 1;
document.getElementById('prices').innerHTML = ( parseFloat(document.getElementById('prices').innerHTML) - price).toFixed(2);
document.getElementById('weight').innerHTML = ( parseFloat(document.getElementById('weight').innerHTML) - weight).toFixed(2);
}
}
<div class="col-md-4 inner-container">
<div class="card border">
<div class="column-image" style=" background-image: url(<?php echo ($value['image']); ?>">
</div>
<h2>
Something
</h2><br/>
<p>Price: £ 3.5
</p>
<p>Weight: 5.2g
</p>
£<span id="prices">3.5</span><br/>
<span id="weight">5.2</span> g<br/>
<button onclick="minus()"> - </button><span id="quantity"> 1 </span><button onclick="plus()"> + </button><br/>
<!-- runs the function addcookie in javascript and passes paramater id -->
<button class="column-button" onclick="addcookie(<?php echo $value['id']; ?>)">Add to basket</button>
</div>

On any select option display only last inserted record

I have a little problem. I have a simple select field and get options from the database when the user clicks on any option I get an input box with the name of the last inserted record from the database, and I need to display the input box with the name of what the user selected not the last record. Code is bellow:
<div class="col-md-6 mb-3">
<label>Odaberite dimenziju produkta</label>
<select class="select2" name="size_id[]" multiple="multiple" id="selectBox" onchange="changeFunc();">
<?php
$get_sizes = "select * from sizes";
$sizes = mysqli_query($con,$get_sizes);
while($row_size = mysqli_fetch_array($sizes)){
$size_id = $row_size['id_size'];
$size_name = $row_size['productSize'];
$i++;
echo "<option value=".$size_name.">".$size_name."</option>";
} ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<div id="textboxcont" style="display: inline-flex; width: 100%;"></div>
<script type="text/javascript">
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues)
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}
</script>
</div>
I need when the user clicks on one of four available selected options to display selected inputs with different names. Now when users select any 1 or 2 or 3 available options they display only the last records from the database. Any help why?
You are having problem here..
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
Your $size_name var contains last value of the query data array that you looped already while adding options to the select.
You should not use that to set attribute while creating input.
You should use the values that you have collected in selectedValues.
You can either itarate through it or use array index like selectedValues[ i ] to set input attribute like below.
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues[0]);
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", selectedValues[i]);
i1.setAttribute("id", selectedValues[i]);
i1.setAttribute("placeholder", "Enter price for " + selectedValues[i] );
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}

How to add strikethrough in the js tree according condition?

I have created a jsTree to show the folder pathname. My problem is how do I add a strikethrough according to the condition active or inactive in the JSTree ? Hope someone can guide me to solve this problem. Below is my code:
<?php
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$arr_sql5 = db_conn_select($folderData);
foreach ($arr_sql5 as $rs_sql5) {
$active = $rs_sql5['status'];
}
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
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='category'>". $row['category']."</span>",
"category" => $row['category'],
"state" => array("selected" => $selected,"opened"=>$opened)
);
}
?> -->
<!-- Initialize jsTree -->
<div id="folder_jstree" title=""></div>
<!-- Store folder list in JSON format -->
<textarea style="" id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea>
<script style="text/javascript">
$(document).ready(function() {
var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());
$('#folder_jstree').jstree({
'core': {
'data': folder_jsondata,
'multiple': false
},
'plugins': ['sort'],
'sort': function(a, b) {
return this.get_text(a).localeCompare(this.get_text(b), 'en', {
numeric: true
});
}
});
var getColor = function(i) {
if (i >= 100 && i <= 199) {
return "blue";
} else if (i >= 200 && i <= 299) {
return "red";
} else if (i >= 300 && i <= 399) {
return "yellow";
} else if (i >= 400 && i <= 499) {
return "purple";
} else if (i >= 500 && i <= 599) {
return "green";
} else {
return "#000";
}
};
var colorNodes = function(nodelist) {
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));
tree.redraw_node(n.id); //Redraw tree
colorNodes(n.children); //Update leaf nodes
});
};
$('#folder_jstree').bind('load_node.jstree', function(e, data) {
var tree = $('#folder_jstree').jstree(true);
colorNodes(tree.get_json());
});
$('#folder_jstree').bind('hover_node.jstree', function(e, data) {
$("#" + data.node.id).attr("title", data.node.original.category);
});
});
/* $(function() {
$(document).tooltip();
}); */
</script>
Inside json_encode($folders_arr) the content is:
[{"id":"1","parent":"#","text":"100 PENTADBIRAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"2","parent":"#","text":"200 PENGURUSAN TANAH & BANGUNAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":true,"opened":true}},{"id":"3","parent":"#","text":"300 PENGURUSAN ASET <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"4","parent":"#","text":"400 PENGURUSAN KEWANGAN <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"5","parent":"#","text":"500 PENGURUSAN SUMBER MANUSIA <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"6","parent":"1","text":"100-1 PERUNDANGAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"7","parent":"1","text":"100-2 PERHUBUNGAN AWAM <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"8","parent":"6","text":"100-1-1 PENGGUBALAN-PENYEDIAAN-PINDAAN UNDANG-UNDANG-PERATURAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"9","parent":"6","text":"100-1-2 KHIDMAT NASIHAT <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"10","parent":"8","text":"100-1-1-1 UNDANG-UNDANG KECIL KERJA DI JALAN 1996 <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"11","parent":"8","text":"100-1-1-2 UNDANG-UNDANG KECIL PERUNTUKAN MENGENAI LESEN BERSESAMA (MAJLIS PERBANDARAN) <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"12","parent":"8","text":"100-1-1-3 UNDANG-UNDANG KECIL MENGKOMPAUN KESALAHAN-KESALAHAN (MAJLIS PERBANDARAN KLANG), JALAN PARIT DAN <span id='category'>JTM (BERHUBUNG KOD 100-1\/1\/2)<\/span>","category":"JTM (BERHUBUNG KOD 100-1\/1\/2)","state":{"selected":false,"opened":false}},{"id":"13","parent":"9","text":"100-1-2-1 JABATAN PENGUATKUASAAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"14","parent":"9","text":"100-1-2-2 JABATAN BANGUNAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"15","parent":"7","text":"100-2-1 PUBLISITI, PROMOSI DAN PROTOKOL <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"16","parent":"15","text":"100-2-1-1 PUBLISITI DAN KENYATAAN MEDIA <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"84","parent":"#","text":"201 HAHA <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}}]
I want the condition such that if $active = 0 then it will show the strikethrough in the jsTree. Else if $active = 1 then it will back to normal.
Actually I want the actual output like the below sample picture. For the output below I just used Paint software to edit, easier to let you know what I want as the output:
My working JSFiddle code is here: https://jsfiddle.net/ason5861_cs/9x0dsotz/2/
Hope someone can guide me on how to add strikethrough according to the condition active or inactive into my code?
Note:$row['name'] and $row['category']needed to put strikethrough together if inactive.
With PHP you could have your conditional to set the value of a NULL variable to text-decoration that changes to line-through. This would be done with CSS. Simply have a conditional that checks if the value of $active is set to 0, if it is, then set the value of the null variable to display line-through. If the value of active is anything other than 0, then $strikeThrough will stay NULL and output nothing, therefor no change to text style that is wrapped in span tag.
$strikeThrough = null;
if($active = 0){
$strikeThrough = 'text-decoration: line-through;'
$output = "<span style='".$strikeThrough."'>" . $rs_wtpname . "</span>";
}
// no change needed for default Active
IN JS, you could use the #folder_jstree nodelist to run through your list and update there. Likely within your colorNodes function you could have a conditional there to check the value of status, then append css to your value if set to 0 (inactive).
If you are unable to get the status from PHP into JS, you could dump the value in the php code using the aforementioned method into an arbitrary data attribute or even alt attribute added to the #folder_jstree element span tag. Then retrieve that using JS and perform your conditional in JS.
EDIT: (April 25th, 2020)
Okay I think I see what you are doing with the JSON and your $folders_array now and how it is saving the data to be parsed in the JSON file.
Try the following code in your php and see if it works.
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$arr_sql5 = db_conn_select($folderData);
foreach ($arr_sql5 as $rs_sql5) {
$active = $rs_sql5['status']; //--> Here you are setting active state
}
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
//--> this would be the default state of active = 1 set in $output
$output = $row['name'] . ' ' . "<span id='category'>". $row['category']."</span>";
//--> Now we see if active is set to 0
if($active === 0){
//--> if active is set to 0 change the value of $output to reflect 'text-decoration'
$output = "<span style='text-decoration: line-through;'>" . $row['name'] . ' ' . "<span id='category'>". $row['category']."</span></span>";
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $output, //--> save the proper $output in our array
"category" => $row['category'],
"state" => array("selected" => $selected,"opened"=>$opened)
);
}

How do I make a standalone repeating jQuery function

I have been working on a filter function in jQuery for a simple unordered list. Each list is inside a block with a filter that can be modified in the back-end (Wordpress) to filter out specific strings. The filter also has a reset button to set it back to the original state.
Now I've been asked to make this a repeatable list. Repeating the list itself wasn't a problem but the filter now filters out items in all existing lists.
So the filter does work but it gets a bit overexcited filtering out all elements that have the class filter-list_item. I thought adding a number to the class on the parent div on each loop and then adding a for loop in jQuery to target these specific classes would fix this. Hence the $list_count and listCount variables. This however does the exact same thing and still affects all lists. I'm not sure why. Any help on how to make it so that the filters only filter out items in their corresponding lists would be much appreciated.
This is the current jQuery for the filter function:
$(document).ready(function (){
// Content filter
var lists = $(".filter-list").length;
for(var listCount = 0; listCount < lists; ) {
$(".filter-list-"+listCount).find(".content-filter").change(function() {
// Retrieve the option value and reset the count to zero
var search = $(this).val(), count = 0;
$(".filter-list_item").each(function(){
// Remove item if it does not match the value
var string = this.innerText;
var found = strSearch(search.toLowerCase(), string.toLowerCase());
if (found) {
$(this).css("display", "block");
// Show the list item if the value matches and increase the count by 1
count++;
} else {
$(this).css("display", "none");
}
// Show reset button
if($(this).index() > 0) {
$(".filter-reset").addClass("active");
}
});
// Update the count
if(count == 0) {
$(".filter-select-results").text("No results for " +search);
} else if(count > 0) {
$(".filter-select-results").text('');
}
});
// Reset filter
$(".filter-reset").click(function() {
$(".content-filter").prop('selectedIndex',0);
$(".filter-list_item").css("display", "block");
$(".filter-reset").removeClass("active");
$(".filter-select-results").text('');
});
listCount++;
}
});
// Search function
function strSearch(search, string) {
var n = string.search(search);
if(n >= 0) {
return true;
}
return false;
}
And this is the PHP used to build the lists
<?php
$list_count = 0;
foreach ($layout['list'] as $list) { ?>
<div class="container filter-list filter-list-<?php echo $list_count++; ?>">
<div class="title-wrapper">
<h2><?php echo $list['title']; ?></h2>
<?php echo $list['description'];
// Content filter
if($list['content_filter'] == true) { ?>
<div class="filter-container">
<button class="filter-reset"><i class="fa-icon fa fa-undo"></i></button>
<select class="content-filter" name="filterselect">
<option value="all" disabled selected>Selecteer een locatie</option>
<?php foreach($list['filter_options'] as $filter) { ?>
<option value="<?php echo $filter['option']; ?>"><?php echo $filter['option']; ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
</div>
<div class="filter-select-results"></div>
<ul class="filter-list_items">
<?php foreach($list['list_items'] as $list_item) { ?>
<?php if( $list_item['link'] ) { ?>
<li class="filter-list_item"><?php echo $list_item['item']; ?></li>
<?php } else { ?>
<li class="filter-list_item">
<span><?php echo $list_item['item']; ?></span>
</li>
<?php } ?>
<?php } ?>
</ul>
</div>
Replace $(".filter-list_item").each(function(){ with $(this).closest(".filter-list").find(".filter-list_item").each(function(){
This is assuming .content-filter-element is part of a .filter-list. closest then navigates to the first parent satisfying the condition. Whether that condition holds is a bit unclear from the php code you showed.

Send value of button to JS to load DIV content

I am trying to send the value of the selected option to an new DIV to dynamic load an drop down menu.
The DIV is triggered but the needed value is not send to this new DIV.
The problem is + $("#add_bedrijf_" + [i]).val()
What is the correct wat to send this?
(The other code is for manipulating the different classes, this is working correct.)
<div class="form-group col-md-6">
<div class="form-group has-warning-add has-feedback" id="div_add_bedrijf" data-toggle="buttons">';
$c = 0;
foreach ($_SESSION['bedrijf'] as $value)
{
echo '<label class="btn btn-secondary" for="add_bedrijf_<?php echo $c;?>"><input type="radio" id="add_bedrijf_<?php echo $c;?>" name="add_bedrijf" value="'.$value.'" onmousemove="validate_add()" onblur="validate_add()"><img src="images/logo_'.$value.'_small.png" height="30"></label>';
$c++;
}
echo '<span class="glyphicon glyphicon-warning-sign form-control-feedback" id="add_bedrijf_status"></span>
</div>
</div>
<script type="text/javascript">
function validate_add()
{
// Parent div of all buttons
let div_add_bedrijf = document.getElementById('div_add_bedrijf');
// Status div
let add_bedrijf_status = document.getElementById('add_bedrijf_status');
// A list with all the inputs that start the with id "add_bedrijf_"
let elements = document.querySelectorAll('input[id^="add_bedrijf_"]');
for(let i = 0; i < elements.length; i++) {
let element = elements[i];
// If the element is checked
if(element.checked) {
div_add_bedrijf.className = "form-group has-success has-feedback";
add_bedrijf_status.className = "glyphicon glyphicon-ok form-control-feedback";
$("#add_groep").load("includes/dynamic_drop/magazijn_magazijn_groep.php?choice=" + $("#add_bedrijf_" + [i]).val())
// We found one was selected, so exit the loop
return;
} else {
div_add_bedrijf.className = "form-group has-warning has-feedback";
add_bedrijf_status.className = "glyphicon glyphicon-warning-sign form-control-feedback";
}
}
}
</script>
Did you try + element.value instead of + $("#add_bedrijf_" + [i]).val()?
https://www.w3schools.com/jsref/prop_radio_value.asp

Categories

Resources