If <li> contains specific text, return false - javascript

I have this HTML and I'm trying to return false on click if the element contains specific text.
This is my HTML:
<ul>
<li id="1"></li>
<li id="2"></li>
<li id="3"></li>
<li id="4"></li>
<li id="5"></li>
<li id="6">text</li>
<li id="7"></li>
</ul>
Javascript:
$("ul").on('click', 'li', function (e) {
var value = $(this).attr('id');
if ("#" + value + ":contains(\"text\")"){ // Something similar to this
return false;
};
alert('test');
});
How can I return false, if the element contains the word 'text'.
Example: http://jsfiddle.net/wSvLD/ (this returns false on everything)

You'll need to escape those quotes in contains("text")
Or use single quotes in combination with double quotes....
Also, the value var should be inside the event function.
EDITS:
$("li").click(function (e) {
var value = $(this).attr('id');
if ( $('#' + value + ':contains("text")').length != 0 ){
return false;
}
alert('test');
});
:contains returns a jQuery object, so you need to check the length of the object to see if it contains a match.
http://jsfiddle.net/8NuvP/

You were pretty close!
$("ul").on('click', 'li', function (e) {
if($(this).text() == "text"){
return false;
};
alert('test')
});

Try this:
$('li:not(:contains(text))').click(function() {
alert('test');
});

$("li").click(function(){
$(this).text() == "text" ? return false: return "something else";
});
but if what you want to do is to use a click function on all BUT the one with "text", you should do this:
$('li:not(:contains("text"))').click(function(){
//whatever you are trying to achieve
});

Related

How can I restrict results to exact match when jQuery .match() is returning partial match from list items?

I have a jQuery filter function that searches an unordered list for any exact match and then removesClass if found. However some list items may contain values that partially match such as AI and AI Ethics. If searcing for AI it will return both, and if searching for AI Ethics it will only return AI Ethics.
I expect if the user searches for AI it will only return an item with an exact tag AI and not AI Ethics.
UPDATE: I'm posting the most recent version of this filter script as I did make the change from .filter() to .each() and modified it for readablity.
$(function () {
$('#SelectBox-ByType').change(function () {
let typeKey = $(this).val();
if (typeKey) {
$('ul.tags').each(function (i, e) {
let typeValue = $(this).text();
if (typeValue.match(typeKey)) {
$(this)
.parents('.knowledgeBaseItemWrapper')
.removeClass('hideByType');
} else {
$(this)
.parents('.knowledgeBaseItemWrapper')
.addClass('hideByType');
}
});
} else {
$('.knowledgeBaseItemWrapper')
.removeClass('hideByType');
}
parseItems.process();
});
});
I've also tried
if (typeValue === typeKey)
However this won't work because the list can be long and have many different tags. As soon as one item in the list doesn't match the filter fails even when the correct item is there. At least with .match() I'm getting partially accurate results.
Any ideas on how I might modify this filter to return only an exact match when it's in the list?
UPDATE:
The answers so far have focused on filtering each li in the ul. This current function does not have that problem, in its current implementation it works just fine at filtering all li in the ul.
The question is about parsing individual li when their content starts with a partial match.
Below is a partial list of the HTML Dropdown menu:
<div class="col-xs-12 col-md-6 form-group">
<label for="SelectBox-ByType">Categories:</label>
<div class="select-input">
<select name="SelectBox-ByType" id="SelectBox-ByType">
<option value="" selected>Select a Category...</option>
<option value="AI">AI</option>
<option value="AI Bias">AI Bias</option>
<option value="AI Ethics">AI Ethics</option>
<option value="AI Facial Recognition">AI Facial Recognition</option>
<option value="Antitrust">Antitrust</option>
<option value="Augmented Reality">Augmented Reality</option>
<option value="Big Tech">Big Tech</option>
This is an example of the HTML that is being searched:
<div class="knowledgeBaseItemWrapper" id="id1529224">
<div class="knowledgeBaseItem standardContent">
<div class="summaryWrapper">
<div class="titleAnchor">...</div>
<div class="summary">...</div>
<ul class="tags">
<li class="tag">AI Facial Recognition</li>
<li class="tag">Data Privacy</li>
<li class="tag">Big Tech</li>
</ul>
What I need is a way to parse the content and I suspect that my problem is with the if statement match logic:
if (typeValue.match(typeKey))
Try to use .startWith() string method, seems the one that you are looking for:
$(function () {
$("#SelectBox-ByType").change(function () {
let typeKey = $(this).val();
if (typeKey) {
$("ul.tags").filter(function (i, e) {
let typeValue = $(this).text();
if (typeValue.startWith(typeKey)) {
$(this)
.parents(".knowledgeBaseItemWrapper")
.removeClass("hideByType");
} else {
$(this).parents(".knowledgeBaseItemWrapper").addClass("hideByType");
}
});
} else {
$(".knowledgeBaseItemWrapper").removeClass("hideByType");
}
parseItems.process();
});
});
You're using $("ul.tags").filter(...) but that will match the entire <ul>, not the individual <li> elements that I think you want.
Once you change "ul.tags" to "ul.tags li", then each() will address the individual <li> elements and you can then use == instead of match() to test them:
$(function () {
$("#SelectBox-ByType").change(function () {
let typeKey = $(this).val();
if (typeKey) {
$("ul.tags li").filter(function (i, e) {
let typeValue = $(this).text();
console.log( `Testing whether ${typeValue} == ${typeKey}` );
if (typeValue == typeKey) {
console.log( "Yes, they match!" );
$(this)
.parents(".knowledgeBaseItemWrapper")
.removeClass("hideByType");
} else {
$(this).parents(".knowledgeBaseItemWrapper").addClass("hideByType");
}
});
} else {
$(".knowledgeBaseItemWrapper").removeClass("hideByType");
}
parseItems.process();
});
});
you are using filter() which says:
"Reduce the set of matched elements to those that match the selector
or pass the function's test."
Once you have that using a form of a === b will get the exact match then .each() can process those OR you can simply use it like the second example.
Either of these might be simpler but your HTML is not posted to work from.
Note: it is unclear if you require the removal prior to the conditional so I did not do that like:
$(this)
.parents('.knowledgeBaseItemWrapper')
.toggleClass('hideByType', false);
if (typeKey) {
$(function() {
$('#SelectBox-ByType').on('change', function() {
let typeKey = $(this).val();
if (typeKey) {
$('ul.tags').filter(function(index) {
return $(this).text() === typeKey;
})
.each(index, element) {
$(this)
.parents('.knowledgeBaseItemWrapper')
.toggleClass('hideByType',true);
});
parseItems.process();
});
});
$(function() {
$('#SelectBox-ByType').on('change', function() {
let typeKey = $(this).val();
if (typeKey) {
$('ul.tags').filter(function(index) {
return $(this).text()=== typeKey;
})
.parents('.knowledgeBaseItemWrapper')
.toggleClass('hideByType');
parseItems.process();
});
});
});

How to check if a link has some text and evaluate a condition based upon the value of text- Jquery/JS

I want to evaluate a condition based upon a link text and show hide a tab depending on what value it returns.
HTML:
<span class="links">
Info
<a href="#accounts>Accounts</a>
Users
</span>
Here im trying to check if the 'a' has value 'Accounts', if so hide a div.
I tried this:
Js:
var link = $('a').filter( function () {
return $(this).text() =="Accounts";
//will return: [<a href="#accounts>Accounts</a>]
});
And in some place where the 'Accounts' link does not exists, it will return: []
Now Im not sure how to check for a condition whether the array is empty or has a value:
if (link is empty){
//hide ` <a href="#accounts>Accounts</a>`
}else{
//show ` <a href="#accounts>Accounts</a>`
}
Any ideas how this condition can be evaluated?/
Thanks!
You can use the jQuery :contains selector. And since 0 is a falsy value, you can directly compare.
if ($("a:contains('Accounts')").length) {
$("#accounts").hide();
} else {
$("#accounts").show();
}
You can do something like
var link = $('a').filter(function () {
return $(this).text() == "Accounts";
//will return: [<a href="#accounts>Accounts</a>]
});
//link is a jQuery object that has a length property that tells how many dom elements are referred by this jQuery object
if (link.length) {
//show div as
} else {
//hide div
}
Just incase you might have a link with text Accounts in the future in some other part of your page, I would do this:
<span class="links" id="mylinks">
Info
<a href="#accounts>Accounts</a>
Users
</span>
var link = $('#mylinks').find(a).filter(function () {
return $(this).text() == "Accounts";
});
if (link.length) {
//show div
} else {
//hide div
}

Keep appending link value to an input box

I'd like to know how to append link values to an input box. But I can't figure out how to append a new link value to the old one, separated by a space [Fiddle].
<input id="a_input_id" type="text">
<a href="" class="special_field_link">#ABC<a>
<a href="" class="special_field_link">#DEF<a>
<script>
$(function(){
$('.special_field_link').live('click', function()
{
$('#a_input_id').val($(this).html() + '');
return false;
});
});
Should I use something like:
var cur_val = $('#a_input_id').val($(this).html() + '');
if(cur_val)
$('#a_input_id').val(cur_val + "," + new_val);
else
$('#a_input_id').val(new_val);
Your help would be appreciate.
You can use like this,
$('.special_field_link').click(function (e) {
e.preventDefault();
$('#a_input_id').val($('#a_input_id').val()+" "+$(this).html());
});
Use event.preventDefault() to prevent the default click event of anchor. In each click you need to get the current input value, if you want to retain those. In your code, it was overwriting the old with the new values.
Fiddle
If you want to append the value, you could do:
var input = $('#a_input_id');
input.val(input.val() + $(this).html());
And note .live is deprecated, you'd better use .on instead if you switch to a new version of jQuery.
THE DEMO.
You could go with:
http://fiddle.jshell.net/s8nUh/149/
$(function()
{
$('.special_field_link').live('click', function()
{
var original = $('#a_input_id').val();
var val = original + ',' + $(this).html();
val = val.replace(/(^,)|(,$)/g, "");
$('#a_input_id').val(val);
return false;
});
});
$(function(){
$('.special_field_link').live('click', function()
{
$('#a_input_id').val($('#a_input_id').val() + $(this).html() + '');
return false;
});
});
To use best practices, its better to cache jquery object for anchor and also avoid using return false.
$(function(){
var txt$ = $('#a_input_id');
$('.special_field_link').live('click', function()
{
txt$.val(txt$.val() + $(this).html());
event.preventDefault();
});
});

Binding One Click Event to three different links

I wrote a simple script similar to this example. The problem is the click event is only binding to the first #id in the conditional statement. My thought on why this is occurring is there is nothing in each statement to associate the ID with the class in the click function, but when I tried to add a var, the click did not fire at all. Please tell me where I have gone wrong.
Thanks
$(document).ready(function(){
$('.someclass').bind('click', function() {
if('#id1')
{
window.location = "someURL";
}
else if('#id2')
{
window.location = "someURL2";
}
else if('#id3')
{
window.location = "someURL3";
}
});
});
You can check their id's like this
$(document).ready(function () {
$('.someclass').bind('click', function () {
if(this.id === 'id1') {
window.location = "someURL";
} else if(this.id === 'id2') {
window.location = "someURL2";
} else if(this.id === 'id3') {
window.location = "someURL3";
}
});
});
Consider:
<span data-url="someURL">Link 1</span>
<span data-url="someURL2">Link 2</span>
And then:
$wrapper.on( 'click', 'span', function () {
window.location = $( this ).data( 'url' );
});
where $wrapper contains the DOM element which in turn contains all your "links".
The idea here is to separate the data from the JavaScript code (= the behavior). Your URL's should be in the DOM - you can use data-* attributes to store them (as I've shown above).
Since you already use ids for your elements you should use them seperately to bind the click functions. It's easier and it works :)
$(document).ready(function(){
$('#id1').click(function(){
window.location = "someURL";
});
$('#id2').click(function(){
window.location = "someURL2";
});
$('#id3').click(function(){
window.location = "someURL3";
});
});
If you like the original way better (you shouldn't ;-) ) then try this:
if( $(this).attr("id") == 'id1' )
{
window.location = "someURL";
}
I think you are over thinking things and also not knowing what is out there for you to use. I would leverage the data attribute on your links. I'm going to assume they are not your typical A tag with an HREF because you should not use JavaScript if so.
<div data-url="http://www.someurl1.com">...</div>
<div data-url="http://www.someurl2.com">...</div>
<div data-url="http://www.someurl3.com">...</div>
<script>
$('body').on('click','div[data-url]', function(ev) {
ev.preventDefault();
window.location = $(this).data('url');
}
</script>
If my understanding is correct for your requirement, you have a css class called "someclass" which has hyperlinks into it. You need to set the URL of those hyperlinks dynamically through jQuery, am I correct? If so, then you can try the following code:
<script type="text/javascript" src="../Scripts/jQuery/jquery-1.7.2.js"></script>
<script type="text/ecmascript">
$(document).ready(function () {
$(".someclass > a").live("click", function () {
var currentID = $(this).attr("id");
if (currentID == "id1") {
window.location = "http://google.com";
}
else if (currentID == "id2") {
window.location = "http://stackoverflow.com";
}
else if (currentID == "id3") {
window.location = "http://jquery.com";
}
});
});
</script>
<div>
<div class="someclass">
<a id="id1">id 1</a>
<a id="id2">id 2</a>
<a id="id3">id 3</a>
</div>
</div>

How to call and run same function simultaneously from different `<LI>`

How to call and run same function simultaneously from different <LI> using javascript or jQuery.
I want to use same function with different parameters. I want to create like Browser tabs.The multiple tabs are loading simultaneously.
(Sorry, I missed the jquery tag somehow originally.)
Using jQuery:
HTML:
<ul id="mylist">
<li>One</li>
<li>Two</li>
</ul>
JavaScript using jQuery:
$("#mylist > li").click(function() {
// Here, `this` refers to the raw DOM element.
// If you want to know which one it is by index,
// you can use $(this).index() (they start at 0).
// Or you can store information on the element
// using data-* attributes, and use
// $(this).data(...)
});
Live example
Original answer from when I'd missed the jquery tag (doh!):
There's the DOM0 way:
<li onclick="doSomething(1);">One</li>
<li onclick="doSomething(2);">Two</li>
Or there's the unobtrusive DOM0 way:
HTML:
<ul id="mylist">
<li>One</li>
<li>Two</li>
</ul>
JavaScript:
var ul = document.getElementById("mylist");
var li;
var index;
for (li = ul.firstChild; li; li = li.nextSibling) {
if (li.nodeName.toUpperCase() === "LI") {
li.onclick = makeCallback(++index);
}
}
function makeCallback(val) {
return function() {
doSomething(val);
}
}
Or the DOM2 way:
(Same HTML.)
JavaScript:
var ul = document.getElementById("mylist");
var li;
var index;
for (li = ul.firstChild; li; li = li.nextSibling) {
if (li.nodeName.toUpperCase() === "LI") {
hookEvent(li, "click", makeCallback(++index));
}
}
function makeCallback(val) {
return function() {
doSomething(val);
}
}
function hookEvent(element, eventName, handler) {
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent("on" + eventName, handler);
}
Try to use $.each:
$(...).each(function(index, Element) {
...
});
See: http://api.jquery.com/each/
For example:
$(...).each(function(index, Element) {
var target = $(this);
target.click(function() {
// when user click...
});
// something other logic...
});
$('li').click(function(){ var target = $(this);// get your target element
});
And here is the jquery way:
$("li").click(function(){
doSomething($(this).data('someValue'));
});
With the HTML holding the parameters.
<li data-someValue="one">One</li>
<li data-someValue="two">Two</li>
Add a rel attribute to the <li> element, then call the function on the <li>
$('li.your-class').bind('event_type', function(){
var ref = $(this).attr('rel');
// call your function
myFunction(ref);
}
There are quite a few outof the box solutions for this, such as jquery ui. If you wanted to do it manually you could do it fairly easily.
jQuery tabs:
http://jqueryui.com/demos/tabs/
Have your content areas named:
#main_0
#main_1
...
Then add a selector to LI
Something like:
var CurrentTabIndex = null;
$("li").live('click', function(e) {
var TabIndex = $(this).index;
var divName = "#main_" + TabIndex;
$.ajax({
url: "OpenTab.php",
data: { TabId: TabIndex },
success: function (data) {
$(divName).html(data);
$(divName).show();
if(CurrentTabIndex != null)
{
$("#main_" + CurrentTabIndex).hide();
}
CurrentTabIndex = TabIndex;
}
});
});

Categories

Resources