"search" field to filter content - javascript

I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
} ​
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?

$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample

JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/
​

Related

Switch a button depending on check box selection

I currently am building a form that has 3 checkboxes and a dynamic button that appears below.
My current issue is when you select more than one then tick off one more both the active state and deactivate state buttons appear
https://staging-homecarepulse.kinsta.cloud/demo-select/ here is my demo link
Here is the script im using
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if ($(this).is(":checked")) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
here is my html
<input type="checkbox" id="checkbox1" class="mod-link" name="selected" value="es" hidden>
<label for="checkbox1" style="cursor: pointer;">CHECK BOX styling and info HERE</label>
<div class="link-container" style="text-align:center;"></div>
<div style="text-align:center;">
<span class="result_img">
<img id="picture" src="https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg"/>
</span>
</div>
I would like to figure out how to hide the grey image button until ALL OR NO checkboxes are selected. so for short #picture should not display until ALL OR NO CHECKBOXES ARE SELECTED
Any help is appreciated
You can check arr.length earlier for showing and hiding gray button as well. Please see below code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if (arr.length > 0) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
Hope it resolve your issue.

javascript - hide results when input is empty

I have Live Search JSON Data Using Ajax jQuery, and I would like to call more than one JSON file for the search.
At the start of the page, with the input empty, the results are not shown.
However, if you write and delete text again in the input, all results are displayed.
I would like to hide all the results again when the input is empty again.
Thank you in advance.
HTML Input:
<div class="container" style="width:900px;">
<div align="center">
<input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
</div>
<ul class="list-group" id="result"></ul>
</div>
JavaScript:
<script>
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('1.json', function(data) {
$.each(data.entries, function(key, value){
if (value.title.search(expression) != -1 || value.author.search(expression) != -1)
{
$('#result').append('<li class="list-group-item link-class">'+value.title+' <span class="text-muted">'+value.author+'</span></li>');
}
});
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
</script>
$('#search').keypress(function() {
if($(this).val().length > 1) {
// Continue work
} else {
$('#result').html('')
}
Using keypress and keydown check the length before the text change. You can use keyup and change.
It is better to use it with keyup:
$('#txt1').keyup(function() {
if (!$(this).val().length) $('#result').html('');
});
You can also use change:
$('#txt1').change(function() {
if (!$(this).val().length) $('#result').html('');
});
The change will be executed when you click somewhere else on the page.

How to enter all multi-selection options into database

I have multi-selection functionality similar to this (see link): http://jsfiddle.net/eUDRV/341/.
HTML code:
<section class="container" >
<div>
<select id="list" name="list"size="15">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div>
<br><br><br>
<input type="button" id="button_left" value="<--"/>
<input type="button" id="button_right" value="-->" />
</div>
<div>
<select id="selected_values" size="15"></select>
<input name="selected_values" type="hidden"/>
</div>
jQuery/Javascript code:
$(document).ready(function () {
$("#button_right").click(function () {
var selectedItem = $("#list option:selected");
var added = false;
$("#selected_values > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#selected_values"));
updateHiddenField();
});
$("#button_left").click(function () {
var selectedItem = $("#selected_values option:selected"), activeValues;
var added = false;
$("#list > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#list"));
updateHiddenField();
});
function updateHiddenField () {
$('input[name="selected_values"]').val(
$.map($('#selected_values option:selected').toArray(), function (e) {
return e.value;
})
);
}
});
PHP code:
if(!empty($_POST['selected_values'])) {
$_POST['selected_values'] = explode(',', $_POST['selected_values']);
foreach($_POST['selected_values'] as $x) {
$query = "INSERT INTO $table (id1, id2) VALUES ($id1Value, $x)";
db_query($query);
My goal is to iterate through all of the values that are moved into the left column and enter them into a database using PHP. I'm able to get this functionality to work, however, I'm having the exact same issue as seen referenced here: how can I get all options in a multi-options select using PHP?. I'm accessing the values using $_POST["leftValues"] but if the user clicks on one of the options, only that one will be entered into the database. Unfortunately, the accepted solution isn't working for me.
$("form:has(#leftValues)").on('submit', function () {
$("#leftValues option").prop('selected', true);
});
Can someone please explain to me how I can get this solution to work for me or an alternative way of ensuring $_POST["leftValues"] will contain all the options instead of only the selected/highlighted? Any response is greatly appreciated.
You could add a hidden field and update that whenever the lists change.
You'd need to update your html:
<div>
<select id="leftValues" size="5" multiple></select>
<input name="leftValues" type="hidden" />
</div>
and add a function to do the updating:
function updateHiddenField () {
$('input[name="leftValues[]"]').val(
$.map($('#leftValues option:selected').toArray(), function (e) {
return e.value;
})
);
}
And call it in each of your click handlers:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
updateHiddenField();
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected"), activeValues;
$("#rightValues").append(selectedItem);
updateHiddenField();
});
Finally, you can do this in your PHP to get what you originally expected:
$_POST['leftValues'] = explode(',', $_POST['leftValues']);
Finally got it to work. I edited the submit callback, as the original solution suggested.
Added an id to my form tag:
<form id="form" method="post">
When the form is submitted, select/highlight all options in the selected_values list:
$(#form).submit(function () {
$("#selected_values > option").each(function () {
$(this).attr('selected', 'selected');
});
return true;
});

jQuery adding search (ajax, perhaps?) filter to look through spans with prefix

I'm building an icon library where the user on the front end (submitting a form) can select an icon. I managed to get everything working as far as the selection process. Now, the final product will have over 400 icons, and i wanted to add a search (ajax, i guess) or autocomplete input where the user can type a couple of letters and it filter's out those icons.
They search will be filtering out some with a class that has the prefix "icon-".
I started on jsFiddle here: http://jsfiddle.net/yQMvh/28/
an example would be something like this :
http://anthonybush.com/projects/jquery_fast_live_filter/demo/
My HTML Markup:
<div class="iconDisplay">Display's selected icon</div>
<span id="selectedIcon" class="selected-icon" style="display:none"></span>
<button id="selectIconButton">Select Icon</button>
<div id="iconSelector" class="icon-list">
<div id="iconSearch">
<label for="icon-search">Search Icon: </label>
<input type="text" name="icon-search" value="">
</div>
<span class="icon-icon1"></span>
<span class="icon-icon2"></span>
<span class="icon-icon3"></span>
<span class="icon-icon4"></span>
<span class="icon-icon5"></span>
<span class="icon-icon6"></span>
<span class="icon-icon7"></span>
<span class="icon-icon8"></span>
</div>
JS (note: this includes the selection jQuery as well):
var iconVal = $(".icon_field").val();
$('#selectedIcon').addClass(iconVal);
$("#selectIconButton").click(function () {
$("#iconSelector").fadeToggle();
});
$("#iconSelector span").click(function () {
selectIcon($(this));
});
function selectIcon(e) {
var selection = e.attr('class');
$(".icon_field").val(selection);
$("#iconSelector").hide();
$('#selectedIcon').removeClass();
$('#selectedIcon').addClass(selection).show();
return;
}
Will this work for you? http://jsfiddle.net/yQMvh/37/
I've modified your input field slightly (added an id)
<input type="text" id="txt-icon-search" name="icon-search" />
and added this bit of code.
/**
* Holds information about search. (document later)
*/
var search = {
val: '',
icons: function (e) {
// get all the icons.
var icons = $('span[class*="icon-"]');
// assign the search val. (can possibly use later)
search.val = $(e.currentTarget).val();
// let the looping begin!
for (var i = 0, l = icons.length; i < l; i++) {
// get the current element, class, and icon after "icon-"
var el = $(icons[i]),
clazz = el.attr('class'),
iconEnd = clazz.substr(5, clazz.length);
// was the value found within the list of icons?
// if found, show.
// if not found, hide.
(iconEnd.indexOf(search.val) === -1) ? el.hide() : el.show();
}
}
};
$('#txt-icon-search').keyup(search.icons);
One possible way could be to use DataTables, this framework includes a search functionality, its row based tho, could be modified probably. Or if you want to present each icon with some facts like size, name, creator, it would be good maybe. The user could then sort the height etc.
Have a look here
Its a bit heavy weight but have a lot of possibilities for optimization
What you're looking for is something like this: http://jqueryui.com/autocomplete/
Pretty easy and all ready to use. You could pre-populate the available tags with your icons selection. Quick example:
$(function() {
var availableTags = [
"icon-name1",
"icon-name2",
"icon-name3",
"etc."
];
$( "input[name=icon-search]" ).autocomplete({
source: availableTags
});
});
EDIT: of course you can do something much more sophisticated, like displaying a thumbnail/preview of your icon next to each result
EDIT2:
From the sample in your link, I quickly threw something together to have it the way you wanted it:
JSCODE:
<script>
$(function() {
$.expr[':'].Contains = function(a,i,m){
return ($(a).attr("data-index") || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$("input.filterinput")
.change( function () {
var filter = $(this).val();
if(filter) {
$(list).find("span:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("span:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#iconSearch"), $("#list"));
});
});
</script>
Your html code tweaked a little:
<div id="iconSelector" class="icon-list" style="display: block;">
<div id="iconSearch">
<label for="icon-search">Search Icon: </label>
<input type="text" name="icon-search" class="filterinput" value="">
</div>
<ul id="list">
<li><span class="icon-icon1" data-index="red"></span></li>
<li><span class="icon-icon2" data-index="yellow"></span></li>
<li><span class="icon-icon3" data-index="blue"></span></li>
</ul>
</div>
Now if you type "red" you'll get the first span since the search is looking for a match from the data-index attribute. You can replace those with "Facebook", "Twitter", or whatever the name of your icon is.
If you want to directly search from the class name you can do something like this then:
<script>
$(function() {
$.expr[':'].Contains = function(a,i,m){
return ($(a).attr("class") || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) {
$("input.filterinput")
.change( function () {
var filter = "icon-" + $(this).val();
if(filter) {
$(list).find("span:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("span:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
$(this).change();
});
}
$(function () {
listFilter($("#iconSearch"), $("#list"));
});
});
</script>

How to append input value with ,(comma) when li click?

i have HTML like below,
<ul class="holder" style="width: 512px;">
<li id="pt_5uZqW99dmlgmiuCTJiPHDC9T9o2sfz0I"
rel="test1#gmail.com"
class="bit-box">test1#gmail.com
</li>
<li id="pt_9O0pMJDhtNbRgU1vNM8He8Vh9zpJ1tcE"
rel="test2#gmail.com"
class="bit-box">test2#gmail.com<a href="#"
class="closebutton"></a>
</li>
<li id="pt_U8JH5E9y5w4atm4CadEPvuu3wdh3WcBx"
rel="test3#gmail.com"
class="bit-box">test3#gmail.com<a href="#"
class="closebutton"></a></li>
<li id="Project_update_user_id_annoninput"
class="bit-input">
<input type="text" autocomplete="off" size="0" class="maininput"></li>
</ul>
<input id="removeuser" value="" />
I need to store the values of li's in hidden input box when I click that li's.
If I click first two li's i need to store the values like,
<input id="removeuser" value="test1#gmail.com,test2#gmail.com" />
That is i need to append input values every time when i click li's.
i used below one,
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
jQuery("input#removeuser").val(jQuery.map(jQuery(this).parent().attr('rel')).join(","));
});
});
But it does not works.how can i do that?
http://jsfiddle.net/ySV6F/
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
jQuery("input#removeuser").val(jQuery("input#removeuser").val() + "," + jQuery(this).parent().attr('rel'));
$(this).remove();
return false;
});
});​
This fiddle fixes your issue: http://jsfiddle.net/pratik136/zVmwg/
First change I did was move your text within the <a /> tags. This allowed you to click on them as expected.
Next, I changed the JS to:
jQuery(document).ready(function() {
jQuery("a.closebutton").click(function(a) {
var v = jQuery(this).parent().attr('rel');
var t = jQuery("input#removeuser").val();
if (t.indexOf(v) < 0) {
if(t.length>0){
t += ",";
}
jQuery("input#removeuser").val(t + v);
}
});
});​
I addded the additional check to ensure no duplicates are entered, and that a comma is appended only when necessary.
Try:
var arr = [];
$(".closebutton").click(function(e) {
e.preventDefault();
var email = $(this).parent("li").attr("rel");
if( $(this).hasClass("added") ) {
arr= $.grep(arr, function(value) {
return value != email;
});
$(this).removeClass("added");
}
else {
arr.push( email );
$(this).addClass("added");
}
$("input[id='removeuser']").val( arr.join(",") );
});
First I would suggest that instead of using rel attribute (which has a specific meaning in (X)HTML with certain tags) you use html safe data-* attributes
like this:
<li id="pt_5uZqW99dmlgmiuCTJiPHDC9T9o2sfz0I" data-email="mdineshkumarcs#gmail.com"
class="bit-box">mdineshkumarcs#gmail.com</li>
To access this attribute just use jQuery $(elem).attr('data-email')
Now the solution with no duplicates:
jQuery(document).ready(function(){
jQuery("a.closebutton").click(function(){
var value = $(this).parent().attr('data-email');
var values = $("input#removeuser").val().split(',');
var is_in = false;
// already in?
$.each(values, function(i, e){
if(e == value) {
is_in = true; return false; // set and exit each
}
});
if (!is_in) {
values.push(value);
$("input#removeuser").val(values.join(','));
}
return false;
});
})
I've put the working code on jsFiddle so that you can see it in action.
jQuery(document).ready(function(){
jQuery("a.closebutton").bind('click', function(){
var data = $(this).parent().attr('rel');
if($("#removeuser").val() == ""){
$("#removeuser").val(data);
} else {
$("#removeuser").val(", "+data);
}
$(this).parent().hide();
});
});​
Here I'm removing the li once clicked. You may I believe use the .toggle() function to enable users to remove a value from #removeuser as well.
Hope this helps!

Categories