Dynamic search by class name with JQuery - javascript

I want to make a dynamic search input according to the class names in the I'd like to span tags. However, I am having trouble listing the class name I found.
My aim; Displaying the class names matching the value entered in the input into the screen. Would you help me with this topic?
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
$(document).ready(function() {
$("#searchinput").keyup(function() {
var inputvalue = $("#searchinput").val();
var spantags = $("#iconlist span");
if (inputvalue.length == 0) {
spantags.show();
} else {
if (spantags.hasClass(inputvalue)) {
$("#iconlist span").hide();
}
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Ara" id="searchinput" />
<div id="iconlist">
<span class="test1">Deneme-1</span>
<span class="test2">Deneme-2</span>
<span class="test3">Deneme-3</span>
<span class="test4">Deneme-4</span>
</div>

You could try and use something like this to display the span where the class matches the input.
spantags.filter(function() {
return $(this).attr("class").indexOf(inputvalue) > -1;
}).show();
Demo
jQuery.expr[':'].contains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
$(document).ready(function() {
$("#searchinput").keyup(function() {
var inputvalue = $("#searchinput").val();
var spantags = $("#iconlist span");
spantags.hide();
spantags.filter(function() {
return $(this).attr("class").indexOf(inputvalue) > -1;
}).show();
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Ara" id="searchinput" />
<div id="iconlist">
<span class="test1">Deneme-1</span>
<span class="test2">Deneme-2</span>
<span class="test3">Deneme-3</span>
<span class="test4">Deneme-4</span>
</div>

In the case that you're looking for an exact match, eg "test1" then you cause use
spantags.filter(":not(." + inputValue + ")").hide()
which says to hide everything that does not have the class you entered
(in the case where you want to match any letter, eg "t", use .attr("class").indexOf as in the other answer.
Updated snippet:
$(document).ready(function() {
$("#searchinput").keyup(function() {
var inputValue = $("#searchinput").val();
var spantags = $("#iconlist span");
spantags.show();
if (inputValue !== "") {
spantags.filter(":not(." + inputValue + ")").hide()
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" placeholder="Ara" id="searchinput" />
<div id="iconlist">
<span class="test1">Deneme-1</span>
<span class="test2">Deneme-2</span>
<span class="test3">Deneme-3</span>
<span class="test4">Deneme-4</span>
</div>

Related

Search Box Results Allow Me To Click To Another Page

const people = [
{name: 'tax overview'},
{name: 'patel'}
];
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
const list = document.getElementById('list');
function setList(group) {
clearList();
for (const person of group){
const item = document.createElement('li')
item.classList.add('list-group-item');
const text = document.createTextNode(person.name.capitalize());
item.appendChild(text);
list.appendChild(item);
}
if (group.length === 0){
setNoResults();
}
}
function clearList(){
while (list.firstChild){
list.removeChild(list.firstChild);
}
}
function setNoResults(){
const item= document.createElement('li')
item.classList.add('list-group-item');
const text = document.createTextNode("No results found")
item.appendChild(text);
list.appendChild(item);
}
function getRelevancy(value, searchTerm) {
if (value === searchTerm) {
return 2;
}else if(value.startsWith(searchTerm)){
return 1;
}else if (value.includes(searchTerm)){
return 0;
}else{
return -1;
}
}
const searchInput = document.getElementById('search');
searchInput.addEventListener('input' , (event) => {
let value = event.target.value;
if (value && value.trim().length > 0){
value = value.trim().toLowerCase();
setList(people.filter(person => {
return person.name.includes(value);
}).sort((personA, personB) => {
return getRelevancy(personB.name, value) -getRelevancy(personA.name, value);
}));
}else{
clearList();
}
});
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">
<span class="fa fa-search"></span>
</span>
</div>
<input autofocus placeholder="Search Topics" class="form-control" type="text" autocomplete="off" name="search" id="search" />
<ul class="list-group" id="list"></ul>
</div>
</div>
I want the search results to take me to another link, like a file. For example I search Tax Overview, then it takes me to taxoverview.html. Another minor problem is that since my search bar is in the navbar, when it displays the results, it pushs my navbar all the way down, and its pretty annoying. Is there anyway to make the results go over the screen and content instead of pushing everything down? Thanks, and any suggestions will be greatly appreciated.

Correct syntax to display a recurrent function in an HTML document

I'm a bit lost as to why this code is not displaying anything, it used to work when I didn't have a wrapper function for the button and I entered the parameter for the factorialize function manually in the script, what am I doing wrong?
HTML
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type ="text" id ="number"/>
<button id="factButton"> Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
Javascript
document.getElementById("factButton").addEventListener("click", function(){
function factorialize() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");
if (input === 0) {
return output.innerHTML = 1;
}
else {
return output.innerHTML = input * factorialize(input - 1) ;
}
}
});
I think your looking for something like this:-
document.getElementById("factButton").addEventListener("click", function() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");
function factorialize(input) {
if (input === 0) {
return 1;
} else {
return input * factorialize(input - 1);
}
}
output.innerHTML = factorialize(input);
});
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type="text" id="number" />
<button id="factButton">Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
this will recursively call your factorialize function and set the output.
I would just write the value to the output each recursive call, while changing the value.
document.getElementById("factButton").addEventListener("click", function() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");
output.innerHTML = ''
factorialize(Number(input))
function factorialize(input) {
return output.innerHTML += '' + ((input === 0)
? 1
: (input * factorialize(input - 1)))
}
});
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type="text" id="number" />
<button id="factButton">Factorialize</button>
<h1 id="factorialized"> </h1>
</div>
document.getElementById("factButton").addEventListener("click", function() {
var input = parseInt(document.getElementById("number").value, 10);
document.getElementById("factorialized").innerHTML = factorialize(input);
});
function factorialize(n) {
return (n <= 0) ? 1 : n * factorialize(n - 1);
}
<div class="factorializing">
<h1> Factorialize a number </h1>
<input type="text" id="number" />
<button id="factButton">Factorialize</button>
<h1 id="factorialized"> </h1>
</div>

How to find span with biggest data-item using jQuery

I have a div with spans inside. They have data-item attr. How to find div with the biggest data-item attr. They are numbers starting from 0. For example I have:
<div class="wrapper">
<span data-num="0">text</span>
<span data-num="1">text</span>
<span data-num="2">text</span>
<span data-num="3">text</span>
</div>
Updated: This is part of my code, it's about uploading files and one of the input fields is multiple. And I show in a div with separate spans image names of the files. Use should add multiple files so I need to find the biggest data-num and increment it for the next file.
function getFiles(document, window, index) {
var inputs = document.querySelectorAll( '.app-file' );
input.addEventListener( 'change', function( e )
{
var fileName = '';
var num = 0;
if( this.files && this.files.length > 1 || $(this).next().next().html()) {
var fileName = [];
for (var i = 0; i < this.files.length; ++i) {
fileName.push(this.files.item(i).name);
var comma = '';
if($(this).next().next().html()) {
comma = ',';
}
divName.innerHTML = divName.innerHTML + comma + '<span class="image_name" data-num="'+num+'">' + this.files.item(i).name + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span>';
num++;
}
} else {
fileName = e.target.value.split('\\').pop();
divName.innerHTML = '<span class="image_wrapper"><span class="image_name" data-num="'+num+'">' +fileName + '</span><span class="glyphicon glyphicon-remove remove-file" data-toggle="tooltip" data-placement="top" title="Remove"></span></span>';
var maxIndexItem = $.makeArray($('#wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="file-name" data-input="corporate_document" id="corporates"></div>
HTML
<div class="wrapper">
<span data-num="0">text1</span>
<span data-num="1">text2</span>
<span data-num="2">text3</span>
<span data-num="3">text4</span>
<span>text5</span>
<span data-num="">text6</span>
</div>
JS
$(document).ready(function(){
var arr = [];
$(".wrapper span").each(function(){
var dataNum = $(this).data("num");
if (dataNum != null) {
arr.push(dataNum);
}
}).promise().done( function(){
var max = Math.max.apply(Math, arr);
alert( $(".wrapper").find("[data-num=" + max + "]").text());
} );
});
Refer Fiddle
I think this code can helps you:
var maxIndexItem = $.makeArray($('.wrapper [data-num]')).reduce(function(result, item) {
return $(item).data('num') > $(result).data('num') ? $(item) : result;
});
alert(maxIndexItem.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<span data-num="0">text 0</span>
<span data-num="1">text 1</span>
<span data-num="2">text 2</span>
<span data-num="3">text 3</span>
</div>

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

Opening input when writing #Q# in textarea

I have textarea. Now, I want to do that once you write "#q + number#" ( e.g. #q1# ), it will create new input field.
For example if you write: "Hello my name is #q1# and my favorite food is #q2#". It will open two input fields.
And when you delete one of those #q + number#, it will delete the same field that was intended to the #q#
For example: if you write "Hello my name is #q1# and my favorite food is #q2#, and the input fields look like that:
<input type="text" q="1" />
<input type="text" q="2" />
and next that I delete the #q1# it supposed to look like that:
and don't delete the value of q="2" input.
How can I do that in jQuery/JavaScript?
Take a look at this quick fiddle http://jsfiddle.net/NgxvP/1/
Here you have something to start playing with
<html>
<head>
<style>
#inputField { position:relative;
width: 200px;
height: 200px;
background-color: #cda;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
// in_array function provided by phpjs.org
function in_array (needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
return true;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
return true;
}
}
}
return false;
}
var addedFields = new Array();
function checkFields(input, charCode)
{
var text = (charCode) ? input.value + String.fromCharCode(charCode) : input.value;
var pattern = /#q[0-9]#/g;
var matches = text.match(pattern);
if (!matches) { matches = new Array(); }
if (addedFields.length>0 && addedFields.length != matches.length)
{
for (var index in addedFields)
{
if (!in_array('#q'+ index +'#', matches))
{
$('#q'+index).remove();
delete addedFields[index];
}
}
}
if (matches)
{
for (var i=0; i<matches.length; i++)
{
var code = matches[i];
var index = code.match(/[0-9]/)[0];
if ( $('#q'+index).length == 0 )
{
addFields(index);
}
}
}
}
function addFields(i)
{
addedFields[i] = true;
var fields = '';
for (var index in addedFields)
{
fields += '<input type="text" q="'+ index +'" id="q'+ index +'" />';
}
$('#inputField').html(fields);
}
</script>
</head>
<body>
<div id="formID">
<form>
<textarea onkeypress="checkFields(this, event.charCode); return true;" onkeyup="checkFields(this); return true;"></textarea>
<div id="inputField"></div>
</form>
</div>
</body>
</html>
EDITED: to avoid appending unordered input text fields, but showing them always ordered by their index, as commented in dfsq answer
I created a jsfiddle for your convenience http://jsfiddle.net/2HA5s/

Categories

Resources