Javascript don't add the class - javascript

hello everyone javascript don't add the class to html
$(".ocmessage").each(function(){
var text = $(this).find('p').html();
if(strpos(text,"<b>"+name+"</b>")!==false) $(this).addClass("quoteme");
});
this code should detect if in <p>...</p> there are name of some member and if there is javascript should add class quoteme
how can i fix it?

I think you mean this. BTW, name isn't defined.
var name = ''; // change the value
if(text.indexOf("<b>"+name+"</b>") > -1) {
$(this).addClass("quoteme");
}

Assuming ocmessage is a div or another contain class.
Take a look at : http://jsfiddle.net/40vv7dbk/
$(".ocmessage").each(function () {
var $this = $(this);
var text = $this.find('p').html();
var name = "Ben"
// Will be -1 if not found.
if (text.indexOf(name) > -1) {
$this.addClass("quoteme");
}
});
What it is doing, is when the document is ready, going through all the Divs with the class ocmessage, looking for a tag, and then checking if a name is in there. If it does, I add the class quoteme.

Your elements with class ocmessage may contain more than one paragraph. So inside the first each-loop we have to do a second loop through all <p> like so:
$(".ocmessage").each(function(){
var $T = $(this);
$T.find('p').each(function() {
var text = $(this).html();
// find username and prevent multiple class adding
if(text.indexOf("<b>"+name+"</b>") > -1) {
$T.addClass("quoteme"); return false; // stop loop when class is added
}
});
});
Working FIDDLE here. Credits to Amit Joki.

This is a very poor way to accomplish the task. Here's the more standard jquery way to do it.
$(".ocmessage").has('p b:contains('+name+')').addClass("quoteme");

Related

jquery - get the id of the closest element?

This is my code which is used to edit an input when clicked on it and then save in the db.
$(document).ready(function() {
$('.editable').on('click', function() {
var that = $(this);
if (that.find('input').length > 0) {
return;
}
var currentText = that.text();
var $input = $('<input>').val(currentText);
$(this).append($input);
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if ($input.val()) {
that.text($input.val());
var div_id = $(this).closest('#commentbox').attr('id');
div_id = div_id.replace('comment-', '');
alert(div_id);
$.post( "updateComment.php", {id: div_id,message: $input.val()})
}
that.find('input').remove();
}
});
});
});
Var div_id is not retrieving it at all.
And I want to retrieve only the number from the id from this however it does not work. I've been trying several solutions and this last one isn't working either
<div id="comments">
<div class="commentbox" id="comment-90">...</div>
<div class="commentbox" id="comment-91">...</div>
</div>
This part of code is basically a problem:
var div_id = $(this).closest('#commentbox').attr('id');
Firstly, you are trying to get closest element from document as this points to document in that part of your code (you meant probably event.target instead).
Secondly, you are trying to find the closest element with id == 'commentbox', as this is what #<selector> means. You should use some other attribute for that purpose - probably best would be some class selector and then use the .attr('id') on it.

How to insert multi values to data-tag

I made a jquery filter function, that filtering the results by data-tags. like this:
<div class="resultblock" data-tag="ios">
<img src="images/osx.jpg" class="itemimg">
<div class="desc">
<div class="desc_text">
lorem ipsum
</div>
</div>
i just want to insert in the data-tag another tags to filter. like this:
data-tag="ios,android,windows"
How can i do that?
I am not sure I fully understand the question you are asking, but I think you could accomplish this via JS.
In your html add a script tag and then you just write some JS to edit or add html tags. Here is an example:
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
Now to sort the data-tag:
just add this code to your HTML file.
<div id="div1">
</div>
<script>
var tag ="ios,android,windows"; //initialize variable
var data = tag.split(","); //this makes an array of ios,andrid,windows
var i = 0;
while (i < 3){
alert(i);
var para = document.createElement("p");
var node = document.createTextNode(data[i]);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
i++;
}
</script>
The best way doing this is to use classes. Adding classes and removing them is much easier than other attributes. The classes should not overlap with other classes used for CSS for example. Adding a prefix to them is even better. Like this:
$(".filter-ios").hide(); // hide all ios elements
$("something").addClass("filter-windows"); // add the class windows to an element
$(".filter-ios").addClass("filter-apple"): // add the apple filter class to the ios filter class elements
$("something").hasClass("filter-samsung"); // check if an element has the filter class samsung
// ...
The classes .filter-* should be used for filtering only, they must not have any CSS attached to them, if there is already classes like that, then just change the prefix filter to something else!
I've just created a little object with two methods .add and .remove. It works like classList DOM method for adding and removing classes. If you add one value twice, it's added only once, also if you remove some not existing class, any error will occure. Hope you'll find it helpful.
var el = document.getElementById('myElem');
multiValues = {
add: function(elem,val){
if(elem.constructor.toString().search('HTML')===-1) return;
if(typeof val !=='string') return;
if(!elem.attributes['data-tag']) elem.setAttribute('data-tag');
var attr = elem.attributes['data-tag'];
var parsed = attr.value.split(',');
var isExist = parsed.some(function(a){
return a === val;
});
if(!isExist) parsed.push(val);
elem.setAttribute('data-tag',parsed.join(','));
},
remove: function(elem,val){
if(elem.constructor.toString().search('HTML')===-1) return;
if(typeof val !=='string') return;
if(!elem.attributes['data-tag']) return;
var attr = elem.attributes['data-tag'];
var parsed = attr.value.split(',');
parsed.some(function(a,b){
if(a===val){
parsed.splice(b,1);
}
elem.setAttribute('data-tag',parsed.join(','));
});
}
};
multiValues.add(el,'window');
multiValues.add(el,'window');
multiValues.add(el,'window');
multiValues.add(el,'android');
multiValues.remove(el,'a');
multiValues.remove(el,'b');
multiValues.add(el,'something');
console.log(el.attributes['data-tag'].value);
<div class="resultblock" data-tag="ios" id="myElem"></div>

Content Editable button in Javascript apply to a class

My goal here is to make multiple divs editable by the click of a button. Is there a way to do this by using a class instead of an ID? I'd like to be able to add the editable class to multiple divs throughout my site. Is there a plugin or module that would be well suited for this task? I don't want to edit the code or formatting in the browser, the text content only.
Your thoughts?
test test test test1
test test test test2
test test test test3
<script>
var editorBtn = document.getElementsByClassName('editBtn');
var element = document.getElementsByClassName('editable');
editorBtn.addEventListener('click', function(e) {
e.preventDefault();
if (element.isContentEditable) {
element.contentEditable = 'false';
editBtn.innerHTML = 'update';
} else {
element.contentEditable = 'true';
editBtn.innerHTML = 'done';
}
});
</script>
getElementsByClassName is going to return an array. You probably want to access your button via ID, and the elements via class.
<script>
var editorBtn = document.getElementById('editBtn');
editorBtn.addEventListener('click', function(e) {
e.preventDefault();
var elements = document.getElementsByClassName('editable');
for(var i =0;i<elements.length;i++){
if (elements[i].isContentEditable) {
elements[i].contentEditable = 'false';
editBtn.innerHTML = 'update';
} else {
elements[i].contentEditable = 'true';
editBtn.innerHTML = 'done';
}
}
});
</script>
you should probably pull the editBtn.innerHTML outside the loop, but, since you are making them all editable, or all not editable, it should work as desired as-is.
Add 'editable' class to to your hearts content.
Edit: The above is just an example of how to modify attributes to elements with a given class name (editable). Whether the attributes you are modifying will achieve your desired goal of making the element allow/prohibit editing, is not guaranteed.
If you want to add a class to a set of divs or elements, use Jquery
$(".classToSelect").addClass("classToInsert")
If this is not what you want, plz clarify your question

How to remove duplicated content/value with jQuery

So, i have span element where i appending some content - sometimes this content is duplicated. How to remove this one value which is duplicate of another ...
This is how looks like my output html:
<span class="some_class">
"value01"
"value01"
"value02"
"value03"
"value03"
</span>
I can't add any function because i have no idea how to do this, can u help me?
If these values are being added by JS code, then You can make sth like this:
http://jsfiddle.net/Sahadar/Nzs52/5/
You just have to make object which will store all strings placed inside this span, then just before insertion check if this inserted string is already in store object.
function(event) {
var textareaValue = textarea.value();
if(insertedTexts[textareaValue]) {
event.preventDefault();
textarea.value('');
} else {
insertedTexts[textareaValue] = true;
someSpan.append("\""+textareaValue+"\"");
}
}
If these values are already inside span, use function as follows:
var someSpan = $('.some_class');
var insertedTexts = [];
var result = someSpan.text().match(/"\w+(?=\")/gm);
result = result.map(function(value) {
return value.substring(1,value.length);
});
result.forEach(function(value) {
if(insertedTexts.indexOf(value) === -1) {
insertedTexts.push(value);
}
});
var newSpanText = "\""+insertedTexts.join('""')+"\"";
someSpan.text(newSpanText);
console.info(result, insertedTexts);
It's rebuilding span text (trimming etc.) but main functinality is preserved.
jsFiddle working copy:
http://jsfiddle.net/Sahadar/kKNXG/6/
Create an array variable
var vals = [];
which keeps track of the items. Then, in your function that appends items to the span check:
if (vals.indexOf("Mynewvalue") > -1) {
// Add to the span...
}

jQuery javascript way of checking if some html exist on page

Before appending more code, I want to make sure:
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
isn't already on the html page inside the div where id='faqs'
<div id='faqs'>
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
</div>
What is the best way of doing this with jquery or javascript?
Thanks
The easiest way would be to use jQuery to select the element, and check the length property of the resulting object:
var anchor = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]')
if(anchor.length == 0) {
// element isn't on the page
}
You could search using indexOf
var inBlock = $('#faqs').html();
if (inBlock.indexOf("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>") == -1) {
$('#faqs').append ("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>");
}
if (!$('a[href$="view=article&id=36"]', '#faqs').length) {
//does'nt exist
}
If the goal is to end up with the a tag as a child in the div tag, and thats it, then don't bother checking, just re add it, like this:
$('#faqs').html('');
$('<a />')
.attr('href', 'index.php?option=com_content&view=article&id=36')
.html('hello')
.appendTo($('#faqs'))​;​
However, if you genuinely need to check if it exists, then you can do something like this:
var exists = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]').length > 0;
UPDATE
Finding the string in the html can be done as follows, but this is not a recommended solution. You may run into issues with different browsers encoding html in different ways etc (tested in chrome):
var stringToFind = 'Hello';
// need to replace the & ...
stringToFind = stringToFind.replace(/&/g, '&');
var exists = $('#faqs').html().indexOf(stringToFind) > -1;
if (exists) {
// do something
} else {
// do something else
}
Here's a working example -> http://jsfiddle.net/Uzef8/2/

Categories

Resources