Delete all divs that has part of a string - jQuery - javascript

Heey all,
I want to delete all divs that contains a part of a string.
How can i achieve this?
My old HTML looks like this:
<div class="article-options_4"></div>
My new HTML looks like this, where 4 is the main article id and 2 is the option id of the article:
<div class="article-options_4_2"></div>
Here is my current jQuery which checked if the clicked article is false:
if(this.checked == false) {
$('.article-options' + '_' + $(this).val()).remove();
}
The problem is that when adding new article options with ajax i need to add an extra id to delete every article item when the main article is unchecked. Atleast i think thats the right way...
The problem i faced with this piece of code is that its only deleted one item and not all with the main article ID thats why i added the id of the article options see the html above.
Im curious how i could solve this!

Use the attribute selector, with a ^ to grab everything that starts with the class name. Do not forget the last _ or else selecting article-options_4 will also pick article-options_40 and article-options_400 and so on.
if(this.checked == false) {
$('[class^=article-options' + '_' + $(this).val() + '_').remove();
}

You may use starting with jQuery Attribute Selector
$("div[class|='.article-options_'" + MAIN_ARTICLE_ID + "']").remove()
The [attribute|=value] selector is used to select elements with the specified attribute starting with the specified value.

Related

Select and get contents of a span with same class as other elements on page

I'm trying to do something seemingly simple but it's turning out more difficult than I thought.
I have on a page 4 span elements (that I have no control over) all with the same class ID (BOfSxb) and I need to edit only two of them - the second and the 4th element. So I'm not sure how to select only those two and before I do that, I need to know the contents of the 2nd or the 4th span element (2 and 4 have identical content). I figured out how to get the contents but I'm getting both combined so if the content is 2,304,400 I'm getting back 2,304,4002,304,400
here's how I was able to get the content so far:
var spanContent = $("span.BOfSxb:contains(2,304,400)").text()
console.log(spanContent); //returns 2,304,4002,304,400 ( I need 2,304,400)
The other problem with the above is :contains has a number I won't know ahead of time.
After I get the content off the second or 4th span, I need to compare it and see what range it falls under and do something else with it. Something like:
if ($(".BOfSxb:contains("+ spanContent + ")").text() >= 0 && $(".BOfSxb:contains("+ spanContent + ")").text() <= 1000) {
$("span.BOfSxb:contains("+ spanContent + ")").replaceWith(finalDiv);
} else if ($(".BOfSxb:contains("+ spanContent + ")").text() >= 1001 && $(".BOfSxb:contains("+ spanContent + ")").text() <= 1000000) {
$("span.BOfSxb:contains("+ spanContent + ")").replaceWith(finalDiv2);
} else {
//something else
}
EDIT: I should add this is actually a Chrome extension that will be doing the editing of the span elements on a page I have no control over.
Thank you for any help!
You can specify the element to grab by using it's index number in relation to it's class. You can do this with the jquery .eq() method.
$(".span.BOfSxb").eq(1).text();
$(".span.BOfSxb").eq(3).text();
You can then use the parseInt(); method to change them into numbers and add them if you wish. The parseInt() method returns an integer from a string. When you get the text from the elements they are not able to be added together because they are not considered numbers, they are considered text strings.
Here's the fiddle: http://jsfiddle.net/atw5z0ch/
If I understood your question, this should work:
HTML:
<span class="span">1234</span>
<span class="span">Other content 1</span>
<span class="span">1234</span>
<span class="span">Other content 2</span>
JavaScript (using jQuery):
var content = '1234';
// Notice:
// (i) content is a string. You should use quotes if you
// directly write the value, as specified here: https://api.jquery.com/contains-selector/
// (ii) Using classes to select objects with jQuery will return an array of elements
var spans = $('.span:contains(' + content + ')');
spans.each(function(i){
var value = parseInt($(this).text());
if(value > 0 && value < 1000){
console.log(value);
}
});
Working JsFiddle: http://jsfiddle.net/3tbag1qs/2/
UPDATE: as #zfrisch suggests, you can also get the spans by their positions. The solution presented here is another way to solve your problem, if you are not sure of the exact order.
You can use :nth-of-type selector. It probably wont work in older browsers though.
https://css-tricks.com/almanac/selectors/n/nth-of-type/

jQuery select input elements in a target form with a certain class

I have several forms in one page, and I wanted to target all input fields in a target form (form ID) that has a certain class in it (Eg."has-error" ).
I though this would do the trick:
target_elem = "#form_b";
$(target_elem + ":input").hasClass("has-error").removeClass("has-error");
No luck so far. I've tried playing w/ filtering as well. tsk
Demo
Simply Use .class selector:
$(target_elem + " input.has-error").removeClass("has-error");
Try this , Let me know if it helps :
$(".has-error").each(function(){
$(this).removeClass("has-error");
});
Live example : http://jsbin.com/yudaseqe/1/edit
No need to use ':'
$(target_elem + " input").hasClass("has-error").removeClass("has-error"); should work
Note that you also can forget about hasClass("has-error")
It will take more time to find input with this class than deleting this class of every input without checking if it exists.
target_elem = "#form_b";
$(target_elem + " input").removeClass("has-error");
try this...
$("input[class*='has-error']",$(target_elem)).removeClass("has-error");
Or use this
$("input.has-error",$(target_elem)).removeClass("has-error");

Jquery or Javascript - Regex Matching Elements by IDs and Changing Others With Similar IDs

An ".each do" loop is creating some html on a rails form.
The loop creates checkboxes with IDs like "foo_1_blah", "foo_2_blah" as well as other elements with similar beginnings and matching numbers in their IDs.
Using wildcards (), when one of these checkboxes matching "_blah" is changed,
If that checkbox's ID matches:
/foo_1_*/
I want to .hide() some input boxes matching:
/foo_1_barx_*/
/foo_1_bary_*/
I do not want to ever hide() the checkbox. In some languages I'd do something like
/foo_(\n)_*/
and then I could get the number with $1 and match
/foo_($1)_barx*/
/foo_($1)_bary*/
... but not sure how to do this in jQuery or javascript with dom-tree traversal.
If there is a way to markup the Rails form to enable this, that would work as well.
In jQuery I believe $("input:not(:checkbox)[id|=foo_1_bar]").hide() would work.
This is selecting all input tags that are not checkboxes (:not(:checkbox)) and have an id starting with foo_1_bar ([id|=foo_1_bar]). I don't think you can use wildcards, but the css selectors can give you some more flexibility. Have a look here and here for more info on css selectors.
I combined jQuery and Javascript's regex to solve this. Here:
http://jsfiddle.net/HbtjZ/31/
The .change() detection combines jquery selectors to detect only changes to the relevant checkboxes. Javascript is used to pull out the number from that checkbox's-ID field and build the string used to ID-select the text div I wish to hide (they are actually input-boxes, but matched by ID in either case).
I did not find a way to regex-select divs and toggle them in tandem, using something like:
var matchString = 'input:not(:checkbox)[id^="foo_' + myNumber + '_"]'
$(matchString).toggle()
That seems to match only one instance - the checkbox, and then ignore it per the 'not';
I used a toggle line per each div matching with the ID to workaround this.
Here it is with a nice breakdown of console.log outputs to check progress
Script:
$(function(){
$("input[type='checkbox'][id^='foo_']").change(function(){
foundID = $(this).attr('id')
console.log('We Found ID ' + foundID);
var myMatch = foundID.match(/foo_(\d+)_barx*/);
var myNumber = myMatch[1]
console.log('We Found Number ' + myNumber);
var matchStringA = '#foo_' + myNumber + '_baz'
var matchStringB = '#foo_' + myNumber + '_bay'
console.log('JQ ID String To Match ' + matchStringA + ' and ' + matchStringB);
$(matchStringA).toggle()
$(matchStringB).toggle()
});
});
HTML:
<input type="checkbox" id="foo_1_bar"/>
<div id="foo_1_baz">
Toggle This Visibility With Checkbox #1 Change
</div>
<div id="foo_1_bay">
Toggle This Visibility With Checkbox #1 Change
</div>
<input type="checkbox" id="foo_2_bar"/>
<div id="foo_2_baz">
Toggle This Visibility With Checkbox #2 Change
</div>
<div id="foo_2_bay">
Toggle This Visibility With Checkbox #2 Change
</div>

Append and remove values in a link

So I am using http://isotope.metafizzy.co to filter out different items on a site. The menu should be a "build up" type where when one category is clicked, it filters to those categories, when the next is clicked it adds those newly clicked categories to the existing filter of categories. When its clicked a second time it should remove that categorie from the filter.
More specifically, I have href with #filter and data-filter=".category-name" I need to have a function that would add ", .another-category" to the end of data-filter value for each of the links with name="filters" (or i can use a class instead of if easier)
<ul>
<li>Kitchens</li>
<li>Bathrooms</li>
<li>Living Rooms</li>
<li>Bedrooms</li>
</ul>
I know this function is wrong and doesnt work but its just some pseudo-code
function addFilter(filter) {
names = document.getElementsByName("filters");
for (var name in names) {
name.data-filter = "existing filter, " + filter; // this should be appended to all data-filters
}
}
so basically when a link is clicked it both filters to that category only (lets say kitchens), but also adds the category to the rest of the data-filters (.bedrooms, .kitchens)
javascript or jquery or anything else i may have not realized could work. the documentation for isotope has the option to filter multiple groups of items, but I need it to filter combinations of individual items. Maybe its possible to modify their combination filters to items instead of groups?
See the following article as placed in this post. It should put you in the right direction.
http://www.queness.com/post/7050/8-jquery-methods-you-need-to-know
Stackoverflow question
jQuery - How to add HTML 5 data attributes into the DOM
Well you tagged jQuery, which makes this easy, but I only see you using JS. Anyway, here's one way and some extra info, hope it helps:
jsFiddle {with replication}
jsFiddle {without}
Script
$('li a[name="filters"]').on("click", function(e) {
e.preventDefault();
$(this).data("filter", $(this).data("filter") + ".another-category");
/* and if i wanted to do it without replicating already existing info:
var f = $(this).data("filter");
if (f.indexOf(".another-category") == -1) f += ".another-category";
$(this).data("filter", f); */
});
HTML
<ul>
<li>Kitchens</li>
<li>Bathrooms</li>
<li>Living Rooms</li>
<li>Bedrooms</li>
</ul>
X-tra NFO
jQuery.data(): Biggest Deference - Returns the value that was set
jQuery's .data(): Biggest Deference - Returns the element that was manipulated

JQuery addclass to another div (but not parent) if no data is found

I have this to add a class to the main table that the report is in if there is no data returned.
$('#report-area table td:contains("Sorry, your search did not return any data")').parents('#report-area').addClass('no-report-data')
However, I have another div area "#report-footer" but it's not inside #report-area. I'd like to also add the .no-report-data class to "#report-footer" as well but in this case I don't think the .parents selector will work. Is there another selector I can use to do this?
ID attributes are unique per-page so you can just say this:
$('#report-footer').addClass('no-report-data');
You could also skip the parents altogether and do them both at once:
if($('#report-area table td:contains("Sorry, your search did not return any data")').length)
$('#report-area, #report-footer').addClass('no-report-data');
Reference link http://visualjquery.com/
I think that this might work
var uglySelector = 'table td:contains("Sorry, your search did not return any data")';
$('#reportArea:has(#report-area ' + uglySelector +'), #report-footer ' + uglySelector).addClass('no-report-data');
I recommend you to avoid that long creepy selector ("table td:contains..."), when you write the message "Sorry..." message, just add a class to that td to distinct it later.
How about something like this? It's not real sexy, but should work....
var $noData = $('#report-area table td:contains("Sorry, your search did not return any data")').parents('#reportArea');
if ($noData.length)
{
$noData.addClass('no-report-data');
$("#report-footer").addClass('no-report-data');
}

Categories