Case insensitive jQuery attribute selector - javascript

I am doing the following using attribute contains selector $('[attribute*=value]')
<input name="man-news">
<input name="milkMan">
<script>
$( "input[name*='man']").css("background-color:black");
</script>
This works for the 1st input but not the second input as "Man" has a capital "M"
How can I make $( "input[name*='man']") an case insensitive selector?

The simplest way to do this is to add a case insensitivity flag 'i' inside the regex part of the selector:
So instead of
$( "input[name*='man']")
You could do
$( "input[name*='man' i]")
JS fiddle: https://jsfiddle.net/uoxvwxd1/3/

You can always use .filter():
var mans = $('input').filter(function() {
return $(this).attr('name').toLowerCase().indexOf('man') > -1;
});
mans.css('background-color', 'black');
The key part here is toLowerCase() which lowercases the name attribute, allowing you to test it for containing man.

var control = $('input').filter(function() {
return /*REGEX_VALUE*/i.test($(this).attr('id'));
});
*REGEX_VALUE* - the value you want to find
I ended up using regex to validate whether the attribute 'ID' satisfy... regex is much more flexible if you want to find a certain matching value or values, case sensitive or insensitive or a certain range of values...

I was just able to ignore jQuery's case sensitivity altogether to achieve what I want using below code,
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
You can use this link to find code based on your jQuery versions,
https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
Also there is an article where it does to many good things with jQuery: http://www.ultechspot.com/jquery/using-jquery-search-html-text-and-show-or-hide-accordingly

This works for me using jQuery and if i'm adding item to a table
// check if item already exists in table
var inputValue = $('#input').val(); // input
var checkitem = $('#exampleTable td.value div.editable').filter(function() {
//check each table's editable div matches the input value in lowercase
if ($(this).text().toLowerCase() === inputValue.toLowerCase()) {
itemexists = true;
}
});
if (itemexists) {
alert("item exists in the table");
return;
}

Related

jQuery add/remove text from input string

I have a function that adds text into an input box. Basically you click a div and it activates the function by onclick="addvalue(“Name”)"
function addvalue(newdate){
var input = $("#datestobeexcluded");
input.val(input.val()+","+newdate);
};
But what I really need to do is to check the string inside the input value,
If it’s not there to add the text, which it does, and remove it if text is already present in string.
I am not doing well with jquery at the moment. Thank you in advance
var input = $("#datestobeexcluded");
if(input.val().search(newdate) >= 0)
{
input.val(input.val().replace(newdate,''));
}
else
{
input.val(input.val()+","+newdate);
}
And if you have multiple occurrences:
input.val(input.val().replace(/newdate/g,''));
You can use includes with RegExp:
var input = $("#datetobeexcluded");
input.val(input.val().includes(newdate) ? input.val().replace(new RegExp(newdate, "g"), "") : `${input.val()},${newdate}`);
You may replace your inline on click binding with jQuery styled click listener.
Then you may use the next code.
const $input = $('#your-input')
$('.extra-option').click(function() {
const inputString = $input.val()
const content = inputString ? inputString.split(',') : []
const stringToAdd = $(this).html()
const stringIndex = content.indexOf(stringToAdd)
if (stringIndex === -1) {
content.push(stringToAdd)
} else {
content.splice(stringIndex, 1)
}
$input.val(content.join(','))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="your-input" type="text" />
<div class="extra-option">Name</div>
<div class="extra-option">Company</div>
<div class="extra-option">Address</div>
At first, you need to figure out how you will provide clicked element value. Your approach is definitely wrong because you need to bind function on click, while you return undefined. For test purposes I use innerText.
At the second, you need to check if your string contains clicked div string or not. To simplify this logic, I use splitting by delimiter and then manage with an array of entries.
The last step, you need to update your input value.
I guess it's all.
Let me know if you have any question.

Finding a span where the class contains a text string JQuery

I am using JQuery to find a span element that contains a string of text in the class, but could also contain other text.
var not_breaks = element.filter("span.this_text");
This works for spans where class="this_text" but not class="this_text_and_more_text" - I need to search for both.
In that case you could use the Attribute Contains selector:
var not_breaks = element.filter("span[class*='this_text']");
You could also use the Attribute Starts With selector, but note that this is only guaranteed to work if the element has a single class on it:
var not_breaks = element.filter("span[class^='this_text']");
We can get all the span class with the name by using a hasclass, Will this help you
var pare=$('span');
$( pare ).each(function() {
if($(this).hasClass('httext')){
alert($(this).html())
}
});
I need to search for both
I'd do that with a selector group:
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
// first ---^ comma ---^ ^---- second
That will retain elements matching either selector in the group.
Example:
var element = $("span");
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
not_breaks.css("color", "green");
<div><span>Not a match</span></div>
<div><span class="this_text">this_text</span></div>
<div><span>Not a match</span></div>
<div><span class="this_text_and_more_text">this_text_and_more_text</span></div>
<div><span>Not a match</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use regex to retrieve the any sequence as you need.
var regex = new RegExp("this_txt");
var elem = $("span").filter(function () {
return regex.test($(this).attr('class'));
});
console.log(elem.length);
regex.test function will only return true if the sequence exists.
here's the fiddle
https://jsfiddle.net/yt1cr2zb/

Disable button if a string is matched from a line in jquery

I'm trying to build a website using jquery-1.10.2 where I want to block css related strings like <style>, <link> etc. I want to disable the submit button if any of those strings match. So far I've managed to block them using .keyup() function but if I write more than those tags like <link rel="stylesheet" href="css/bootstrap.min.css"> then it won't work. Here are my codes,
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
if (input == "<style>" || input == "</style>" || input == "<link>") {
$('#deactivedivEditor-2').attr("disabled", "disabled");
}else{
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
JSFiddle Demo
How can I disable the button if any of those strings match from any lines? Need this help badly. Thanks.
You can use regex to check if the text contains certain pattern.
$(document).ready(function () {
var regex = /<\/?style.*?>|<link.*?>/;
$('#inputdivEditor-2').keyup(function () {
var val = $(this).val();
$('#deactivedivEditor-2').prop('disabled', regex.test(val));
});
});
Demo: http://fiddle.jshell.net/tusharj/52xd3s11/
Regex
/ : Delimiters of regex
\/?: Matches 0 or 1 /
.*?: Matches any character any no. of times
|: OR in regex
You can use the following regex to match those strings.
var regex = /<(style|link)>/;
To disable update when the elements are present. That however wouldn't solve all cases. If someone wants he can bypass the regex by writing < style > or with using different encoding and so on.
In my opinion a better option is to look at the content from a browser's perspective. In other words take the input and make an element out of it:
var dummyElement = $('<div></div>');
dummyElement.html(input); //contents of the input field
if(dummyElement.find('style').length > 0) {
//you get the point
}
..because there's that one question on SO, which explains why not parse HTML with regexes..
RegEx match open tags except XHTML self-contained tags
Just use regex to check anything between < > like below:
DEMO
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
var regex=/<*>/;
if (regex.test(input)) {
$('#deactivedivEditor-2').attr("disabled", "disabled");
} else {
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
You can use .prop('disabled',true) for disable button and .prop('disabled',false) for enable button. Both are used after $('#deactivedivEditor-2').
First of all, you can use regular expressions to check the string with a pattern at any position. The regexp I show below matches on anything between two angular braces - even non html tags too.
Secondly - it is a bit off topic - the best and recommended solution for setting and disabling the "disabled" attribute with jquery is by using the .prop() method
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var inputValue = $(this).val();
var regexp = /]*?>/;
var isDisabled = regex.test(inputValue);
$('#deactivedivEditor-2').prop("disabled", isDisabled);
});
});

How to find td element id with value x?

I need to find exactly that td row which contains value priview '2'
I know the td row first half id, but it is dynamic: MovementNumber_M_* (Where * can be from 1 to Milion)
So need to search all rows from MovementNumber_M_1 to MovementNumber_M_9999 which contains MovementNumber_M_*.value=2 and returning directly that td row id which contained that value.
Can you help me? Thanks in advice.
Right and helpfull answers guaranteed ;)
//EDIT
function DgIdOnClick (e,r){
var MovementNumber = document.getElementById(e).value;
//alert('MovementNumber: '+MovementNumber+' Type :'+r);
var result = $('[id^="MovementNumber_M_"][value='+MovementNumber+']');
result.each(function(){
alert($(this).attr("id"));
});
}
OK value=1 is for init and thats why are alerting all rows but if value is 2 then jq is not finding him WHY ?
The function DgIdOnClick is inicialized #
$( document ).ready(function() {
var SecondDiagnosis=$( "span[id^='lov_Dg2Id_D_']" );
var SpanBlock2=SecondDiagnosis.find('a');
var eventH2=SpanBlock2.attr( "onclick" );
SpanBlock2.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(12)).id,2);"+eventH2);
var FirstDiagnosis=$( "span[id^='lov_DgId_D_']" );
var SpanBlock=FirstDiagnosis.find('a');
var eventH=SpanBlock.attr( "onclick" );
SpanBlock.attr("onclick", "DgIdOnClick(document.getElementById('MovementNumber_D_'+parentElement.getAttribute('id').substring(11)).id,1);"+eventH);
});
function DgIdOnClick is on other .js file
If i am alerting IN DgIdOnClick alert(document.getElementById('MovementNumber_M_2').value)//MovementNumber_M_2 Then value is 2 but jq is not founding it
This alerts the ID's of each row containing that value
var result = $('[id^="MovementNumber_M_"][value="2"]');
result.each(function(){
alert($(this).attr("id"));
});
http://jsfiddle.net/q8QaG/
Update:
This alerts the id of all inputs with the value of 2, even on input update
$("#button").click(function(){
$('[id^="MovementNumber_M_"]').each(function(){
var value = $(this).val();
if(value == 2){
alert($(this).attr("id"));
}
});
});
http://jsfiddle.net/q8QaG/3/
$('#TableID').find('td').filter(':contains("SOME_TEXT")');
The previous 2 answers have the string encoding similarly incorrect. This should be it:
$('[id^="MovementNumber_M_"][value="2"]');
You can use combination of Attribute Starts With Selector [name^="value"] and Attribute Equals Selector [name="value"]
var myElement= $("[id^='MovementNumber_M_'][value=2]");
As per comment, if you need id use attr()
var myElementId = $("[id^='MovementNumber_M_'][value=2]").attr('id');

jQuery selector, contains to equals

I have the folowing selector
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option:contains('LIKE')");
this checks for an option which contains the word 'like' right?
How do i find an option which is exactly with the word 'like'?
Somthing like this:
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option:equals('LIKE')");
Just select all the options from the select and filter them by text() value:
var likeComperssionOption = $('select[id*=ComparisionType]:first option').filter(function() { return $(this).text() == "LIKE" });
If you want to select based on the value attribute of the options, you need to use the attribute equals selector to select elements with a specific value for their value attribute:
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option[value='LIKE']")
Otherwise, to select based on the display text of the options, use:
var likeComperssionOption = $('select[id*=ComparisionType]').eq(0)
.find("option").filter(function() {
return $(this).text() == 'LIKE';
});
Update: You might be having some problems with your initial selector, it looks very strange. You should probably change
$('select[id*=ComparisionType]').eq(0)
to something simple like
$('#ComparisionType')
The concept of this answer works fine, you can see it in action here.

Categories

Resources