I've been trying to call a user defined JavaScript function on a jQuery element, and though I've seen several topics on here about it, I'm still having a bit of trouble applying their logics to my situation. Here's what i've tried so far:
Javscript & jQuery:
$(document).ready(function() {
// JavaScript function
nl2br = function (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
// jQuery Call
if ( ! $('.mediaDesc:contains("p")').length || ! $('.mediaDesc:contains("div")').length || ! $('.mediaDesc:contains("span")').length ) {
nl2br(this);
}
}); //end document ready
HTML:
<div class="mediaDesc">
Hello World!
I am text on a new line soon to have a br tag before me!
</div>
My goal is to dynamically find div's with a class of mediaDesc to see if their inner content contains html tags such as p,span, or div. If not, then apply the nl2br JavaScript function to it. Any help would be appreciated. Thanks in advance.
ifcondition satisfied? Do the selectors find the elements you expect them to find? Does your function get called? Step through this in a debugger, you'll be able to find useful information to help us assist you.thistonl2brbut the argument looks like it requires a string (the content you are trying to affect). IOW it seems perhaps you want something more like thisnl2br($(this).html());jQuery(function($) { ... put your script in here ... });- also, I'm not sure, but I believe you'll need to change fromnl2br(this)tonl2br($(this))- there is a difference... - plus, as @CrayonViolent points out, the nlbr() function is set up to parse a string, but you're passing it the element object...$(this).val(nlbr($(this).val()));