Search if the inputed text exist in select list - javascript

i work with prestashop1.7. The Search by Brand works perfectly under the form "dropdown list" in the module ps_facetedSearch.
I need to override this search instead of dropdown i need an input field, So i think that the solution can be to search if the inputed text is exist in the dropdown list. this is my essay but the console display no despite console log on txtValue and inpted showContent of these variables. that's why i need your help concerning the script js itself that must test if inputed text exist in the dropdown list.
code html of the module faceted search
<div class="dropdown-menu" id="dropdown-menu">
<a rel="nofollow" href="http://archivartshop.local/fr/2-accueil?q=Marque-Naim+Ameur" class="select-list"> Naim Am(1)</a>
<a rel="nofollow" href="http://archivartshop.local/fr/2-accueil?q=Marque-Sonia+Mili" class="select-list"> Sonia Mili (1) </a>
<a rel="nofollow" href="http://archivartshop.local/fr/2-accueil?q=Marque-Yosr+Ben+Hammouda" class="select-list"> Yosr Ben Houda(2)</a>
</div>
My essay script js
function mFn(){
divLi = document.getElementById("dropdown-menu");
linka = divLi.getElementsByTagName("a");
for (i = 0; i < linka.length; i++) {
var txtValue = linka[i].textContent ;
// console.log(txtValue); content displayed
var inpted = $('#search_input').val();
// console.log(inpted);content displayed
if( txtValue === inpted)
{
console.log("it_works");
}
else {
console.log("No !!");
}
}
}
I would be very grateful for your help

Now it works for me
function mFn(){
divLi = document.getElementById("dropdown-menu");
linka = divLi.getElementsByTagName("a");
for (i = 0; i < linka.length; i++) {
var txtValue = linka[i].textContent ;
// console.log(txtValue); content displayed
var inpted = $('#search_input').val();
// console.log(inpted);content displayed
if( txtValue.includes(inpted) )
{
console.log("it_works");
}
else {
console.log("No !!");
}
}
}

Related

choose a link with 2 parameters using javascript

<div>
<p>
<a class="article-link" href="/title1">Title 1</a>
<a class="article-link" href="/title1">year1</a>
</p>
<p>
<a class="article-link" href="/title2">Title 3</a>
<a class="article-link" href="/title2">year2</a>
</p>
<p>
<a class="name-link" href="/title3">Title 3</a>
<a class="name-link" href="/title3">year1</a>
</p>
</div>
I need to automate some function in a website. I want to redirect to the link, if you know the title AND the year, using javascript.
for example: I want to be redirected to the link of title3 and year1.
I tried with this:
function picktitle() {
chrome.storage.sync.get('title', function(data) {
var items = document.getElementsByClassName('article-link');
for(i = 0; i < items.length; i++) {
if((items[i].innerHTML).includes(title)) {
chrome.runtime.sendMessage({redirect: items[i].href});
break;
}
}
});
}
but it choose only the first parameter and i need that it choose the href based on both title and year.
I hope I explained myself.
I'm really sorry if im misunderstanding this, but wouldn't using the && keyword in your if statement be the solution? For example:
if (statement1 && statement2) // only runs if both statement1 AND statement2 are true
// do stuff
Also, maybe select the parent element and check to see if it's children have two elements with the required text properties:
function picktitle() {
chrome.storage.sync.get('title', function(data) {
var items = document.getElementsByClassName('article-link');
for(i = 0; i < items.length; i++) {
if(
// Checks if the parent contains the title and the year
(items[i].parentElement.innerText).includes(title) &&
(items[i].parentElement.innerText).includes(year)) {
chrome.runtime.sendMessage({redirect: items[i].href});
break;
}
}
});
}
I also changed innerHTML to innerText because you probably don't need all the html code with it too.

listen to keypress and add to input form

I am trying to add a search filter to my website, and I would like it to be dynamic without clicking on the input form, i.e. listen to keystrokes.
currently I have the following code:
JS:
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<ul id="myUL">
<li>
<a href="#">
Adele
</a>
</li>
<li>
<a href="#">
Vivian
</a>
</li>
<li>
<a href="#">
Lucy
</a>
</li>
</ul>
I have tried adding the following to my script tag:
window.addEventListener('keypress', function (e) {
document.getElementById("myInput").value += event.key;
});
But:
it doesn't recognize backspace in order to delete from the search
filter.
it doesn't search. I have to press the search box, which I want to eventually hide, in order for the filter to work.
I am pretty new to JS and would like to hear if anyone encountered this or something similar.
Thanks.
I'm not encouraging this interface pattern... but I am encouraging you to have fun - and be creative / which you are doing.
Here's how I'd think about it / loosely. https://jsfiddle.net/sheriffderek/dbr1ku3e/
// "I am trying to add a search filter to my website"
// "and I would like it to be dynamic without clicking on the input form, i.e. listen to keystrokes."
// (1) keep a string in memory - of what is typed - (allow for backspace etc...)
// (2) keyup - filter the menu - based on the string + (3) render the updated list ?
const queryLetters = []; // not really a "string though" - but maybe easier to work with!
let queryString = '';
const $output = document.querySelector('.current-search');
function buildSearchString(letterArray) {
var string = '';
letterArray.forEach( function(letter) {
string += letter; // yes - you could also use map and split instead etc.
})
console.log(`Search for "${string}"`);
return string;
}
function noteQuery(pressedKey) {
if (pressedKey == "Backspace") { // BUT WHAT ABOUT *shift* and other stuff...
queryLetters.pop(); // remove last letter from array
} else {
queryLetters.push(pressedKey);
}
queryString = buildSearchString(queryLetters);
$output.textContent = queryString;
}
const $menu = document.querySelector('[rel="filtered-menu"]');
function collectMenuInfo() {
// go get the HTML stuff... and then we can use it to rerender the list - instead of hiding and showing things....
// assuming this might be server-side rendered to start...
const menuItems = $menu.querySelectorAll('a');
console.log(menuItems);
const itemArray = Array.from(menuItems).map( function(item) {
return { // from NodeList to array... make a new array of 'items'
text: item.textContent,
href: item.href,
};
});
console.log(itemArray);
window.menuItems = itemArray;
}
collectMenuInfo();
function renderMenu(stuff) {
var filteredItems = stuff.filter( function(thing) {
var lowercase = thing.text.toLowerCase();
return lowercase.includes(queryString);
})
var template = '';
filteredItems.forEach( function(item) {
template += `<a href='${item.href}' class='z'>${item.text}</a>`;
});
$menu.innerHTML = template;
}
document.addEventListener('keyup', function() {
noteQuery(event.key);
renderMenu(menuItems); // could combine these into a handler -
});
span {
font-style: italic;
color: green;
}
a {
display: block;
padding: 6px;
}
<p>Type to search for: <span class="current-search"></span></p>
<nav class="menu" rel="filtered-menu">
Adele
Carl
Sheriff
Derek
Vivian
Lucy
</nav>
Use the onchange event. Whenever the value of the input changes the event is fired
https://www.w3schools.com/jsref/event_onchange.asp

How to filter a list and then remove the results from it, using javascript

I have a list that I'm trying to filter, and then remove the filtered results. I found a ready made solution for the filtering in w3schools, but I'm having trouble with removing lines.
My html is here:
<body>
<ul id="project-list">
<li>Please please me</li>
<li>With the Beatles</li>
<li>A Hard Day's Night</li>
<li>Beatles for Sale</li>
<li>Help!</li>
<li>Rubber Soul</li>
<li>Revolver</li>
<li>Sgt. Pepper's Lonely Hearts Club Band</li>
<li>The Beatles (The White Album)</li>
<li>Yellow Submarine</li>
<li>Abbey Road</li>
<li>Let It Be</li>
</ul>
<div data-role="footer" class="ui-grid-a" data-position="fixed">
<div id="myNavbar" data-role="navbar" class="navbar">
<div class="ui-block-a" style="width:auto">
<button id="remove" onclick="listDelete">Remove</button>
</div>
<script>
$("button").click(function () {
$("li").remove(":contains('Beatles')");
});
</script>
<div class="ui-block-b" style="width:70%">
<input type="text" id="search-input" onkeyup="listFilter()" placeholder="Filter list...">
</div>
</div>
</div><!--/footer-->
The filtering function is this
function listFilter() {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('search-input');
filter = input.value.toUpperCase();
ul = document.getElementById("project-list");
li = ul.getElementsByTagName('li');
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
The above code makes the button delete every line containing the word "Beatles". I'm trying to remove the lines that contain whatever goes into search-input, preferably non-case sensitive (just like the filtering). Ideally, I want this to not work when the filter textbox is empty, so that an accidental click on the remove button won't delete the whole list.
I'm using jquery-2.1.1 and jqm-1.4.4
hope this will work for you. Change click event to this. It is still case sensitive:
$("button").click(function () {
var fltr = $("#search-input").val();
if (fltr)
$("li").remove(":contains('" + fltr+ "')");
});
Based on diabolic's answer and Highway Of Life's icontains expression, the non case sensitive way to do this is the following:
Load the following two in your header, in one or two separate files:
function listDelete(){
$("button").click(function () {
var input = $("#search-input").val();
if (input) $("li").remove(":icontains('" +input+ "')");
});
}
// non-case sensitive contains expression
jQuery.expr[':'].icontains = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
Then your button should be like this:
<button id="remove" onclick="listDelete()">Remove</button>

jQuery Search Function

Hi i'm building a project which has a page navigation and search bar in jQuery.
I can't get my search function to work correctly and I'm not certain if it's a problem with the ID element or the each function. I'm getting the ("Sorry, no student's found!") message for anything that is or isn't a match. So i think there could be a problem with the if statement looking for a match in search function--but not sure.
I'm dynamically adding a search box to my html like this:
function appendSearchBox(){
var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
$(".students").after(search);
// Add click event handler
$("button").click(function() {
searchList();
});
}
this is what my html looks like for a list of students:
<div class="page">
<div class="page-header cf">
<h2 class="students">Students</h2>
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
And then here is the actual search function:
var listStudents = $(".student-list li");
var numStudents = listStudents.length;
function searchList() {
var matched = [];
// Obtain the value of the search input
input = $("#search").val()
// remove the previous page link section
$('.pagination').hide();
// Loop over the student list, and for each student…
listStudents.each(function(){
// ...obtain the student’s name…
var name = $(this).find("h3").val();
// ...and the student’s email…
var email = $(this).find(".email").val();
// ...if the search value is found inside either email or name…
if (name.includes(input) || email.includes(input)) {
// ...add this student to list of “matched” student
matched.push($(this).parent());
}
});
// If there’s no “matched” students…
if (matched.length === 0){
// ...display a “no student’s found” message
var message = ("Sorry, no student's found!");
$(".student-list").hide();
$(".student-list").after(message);
if (matched.length > 10) {
// ...call appendPageLinks with the matched students
appendPageLinks(matched);
}
// Call showPage to show first ten students of matched list
showPage(1, matched);
}
}
adding functions which actually show the students and add navigation
function showPage(pageNum, listStudents) {
// first hide all students on the page
pageNum = parseInt(pageNum);
listStudents.hide();
// Then loop through all students in our student list argument
listStudents.each(function(index){
// if student should be on this page number
if ((index >= ((pageNum*10)-9)) && (index <= (pageNum*10))) {
// show the student
$(this).show();
}
});
}
function getNumPages(numStudents){
numPages = Math.ceil(numStudents/10);
return numPages;
}
function appendPageLinks(numStudents) {
// determine how many pages for this student list
pages = getNumPages(numStudents);
// create a page link section
var nav = "<div class='pagination'><ul>"
for (i=1; i<pages+1; i+=1){
nav += ("<li>" + "" + i + "" + "</li>");
};
nav += ("</ul></div>");
$(".student-list").after(nav);
// define what happens when you click a link
var active = $('.pagination a').click(function(){
// Use the showPage function to display the page for the link clicked
var id = $(this).attr('id');
showPage(id,listStudents);
// mark that link as “active”
active.removeClass('active');
$(this).addClass("active");
});
}
here is how i am calling the functions:
appendSearchBox();
showPage(1, listStudents);
appendPageLinks(numStudents);
UPDATE -- I have changed the code to remove the val and put in to grab the text.
Not sure what issue is but it appears if i have a correct match--it is working (since pagination disappears) but the students do not change on the page. If there is no match then I get the error message, but the error console is saying
Uncaught TypeError: listStudents.hide is not a function
at showPage (main.js:8)
I'm not sure if this is somehow related to how I am passing the 'matched' list?
h3 and span tags have no value, but text content, so replace:
var name = $(this).find("h3").val();
// ...and the student’s email…
var email = $(this).find(".email").val();
with:
var name = $(this).find("h3").text();
// ...and the student’s email…
var email = $(this).find(".email").text();
You are using val() method to read inner text of h3 and span (email). It should be text(). Also you are appending message after the student list every time you couldn't find a student. You could have used one span tag and hide/show based on the search results.
function appendSearchBox() {
var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
$(".students").after(search);
// Add click event handler
$("button").click(function () {
searchList();
});
}
$(document).ready(function () {
appendSearchBox();
});
function searchList() {
var listStudents = $(".student-list li");
var numStudents = listStudents.length;
$(".student-list").show();
$("#message").hide();
var matched = [];
// Obtain the value of the search input
input = $("#search").val()
// remove the previous page link section
$('.pagination').hide();
// Loop over the student list, and for each student…
listStudents.each(function () {
// ...obtain the student’s name…
var name = $(this).find("h3").text();
// ...and the student’s email…
var email = $(this).find(".email").text();
// ...if the search value is found inside either email or name…
if (name.includes(input) || email.includes(input)) {
// ...add this student to list of “matched” student
matched.push($(this).parent());
}
});
// If there’s no “matched” students…
if (matched.length === 0) {
// ...display a “no student’s found” message
var message = ("Sorry, no student's found!");
$(".student-list").hide();
$("#message").show();
if (matched.length > 10) {
// ...call appendPageLinks with the matched students
appendPageLinks(matched);
}
// Call showPage to show first ten students of matched list
showPage(1, matched);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="page">
<div class="page-header cf">
<h2 class="students">Students</h2>
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
<span id="message" style="display:none;"><br/>Sorry, no student's found!</span>
</div>

how to get exact text value inside a tag in jquery when entities are used

I have a list inside a anchor tag like this
<a href="#" class = "set_priority" data-value = "{{$candidate->id}}" style="text-decoration: none;">
#if($candidate->priority == "")
<li> Prioritize</li></a><br>
#elseif($candidate->priority == "yes")
<li> Deprioritize</li></a><br>
#endif
I have used entity &nbsp for styling purpose. The above code generate html tag according to the response from the server. So it might look either one of these
<li> Prioritize</li>
<li> Deprioritize</li>
I want to alert something when the list item is clicked. I don't know how to compare when &nbsp is used
$('.set_priority').on('click',function(){
var priority_value = $(this).first().text();
if (priority_value = "Prioritize") {
alert('he Prioritised');
}
else if (priority_value = "Deprioritize") {
alert('Prioritised');
}
});
It always alerts alert('he Prioritised'); whatever may be the condition.
You should use comparison operator instead assignment operator and use trim method to remove spaces.
$('.set_priority').on('click',function(){
var priority_value = $(this).first().text().trim();
if (priority_value == "Prioritize") {
alert('he Prioritised');
}
else if (priority_value == "Deprioritize") {
alert('Prioritised');
}
});
replace &nbsp with empty in temporary variable, then compare it. like:-
var priority_value = $(this).first().text();
var temp = priority_value.replace(/ /gi,'');
if (temp == "DePrioritize") {
alert('he Prioritised');
}
else if (temp == "Deprioritize") {
alert('Prioritised');
}
I think you should set the click handler like this
$('set_property li').on('click', function(){
var priority = $(this).first().text(); // This will give you the actual clicked element
// .... rest is same
});

Categories