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: / (this returns false on everything)
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/wSvLD/ (this returns false on everything)
Share Improve this question edited Dec 2, 2011 at 19:59 jQuerybeast asked Dec 2, 2011 at 19:05 jQuerybeastjQuerybeast 14.5k39 gold badges120 silver badges198 bronze badges 1-
Please don't ever use jQuery's
attr
function. It's spaghetti code. Usethis.id
instead. – user1385191 Commented Dec 2, 2011 at 19:24
4 Answers
Reset to default 1You'll need to escape those quotes in contains("text")
Or use single quotes in bination 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/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
});