can't get new lines of selected text on IE11 - javascript

I am trying to replace some text inside a div using a modal window with a form input but for some reason I can't get it to work on IE11. I've realized that it skips new lines when selecting a piece of text containing a <br>
Here is a working example:
http://jsfiddle.net/8VdE9/3/
The funny thing is that I am using the same code in a different page and it gets the new lines fine, which makes me think that I am missing something.
var isIE11 = !!navigator.userAgent.match(/Trident.*rv\:11\./);
range = window.getSelection().getRangeAt(0);
if(!isIE11){
text = new XMLSerializer().serializeToString(range.cloneContents());
}
else{
text = range;
}
text = new String(text);
var textBr = nl2br(text.toString());
function nl2br (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');
}
Any help would be very appreciated.
Regards

Related

jquery not working in PyQt

I am writing a small desktop app in PYQT python which has a QWeb View browser. I am adding a functionality to this browser that when user select any text using mouse and right click and press show xpath a javascript is executed to find the xpath.
Here is my code :
#pyqtSlot()
def slotshowxpath(self):
text = self.selectedText()
if not text:
QMessageBox.information(self,"information","No Text Selected")
else:
frame = self.page().mainFrame().documentElement()
#print frame.toHtml()
#abc = frame.document()
#abc.evaluateJavaScript("alert('"+self.page().selectedHtml()+"');")
frame.evaluateJavaScript("""var data = window.getSelection().anchorNode.parentNode; getXPath(data);
function getXPath( element ){
alert(element);
var xpath = '';
for ( ; (element && element.nodeType) == 1; element = element.parentNode )
{
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
alert(xpath);
return xpath;
}"""
)
this query is working good till $(element.parentNode).children but not working for $(element.parentNode).children(element.tagName).index(element) + 1, can anybody help me in fixing this issue?
actually the problem was with the alert statement inside the query.its not getting executed inside but when i tried it outside the javascript after returning the value, it start working

Generated HTML by javascript is not formatted correctly

I want to make a input field where I can search for friends in a list, these friends I retrieve from a xml file and I generate them using javascript
The code I generate this with:
friendListInDiv = document.createElement("p");
var link = document.createElement("a");
link.onclick = function() {
openChat(friendsXML[i].textContent)
};
var friendText = document
.createTextNode(friendsXML[i].textContent + ":"
+ statusXML[i].textContent);
link.appendChild(friendText);
friendListInDiv.appendChild(link);
friendDiv.appendChild(friendListInDiv);
Now the problem I'm facing I have demonstrated in a jsfiddle:
https://jsfiddle.net/x897pv9o/
As you can see if you type in "j" in the top input bar it hides all friends but type "j" in the bottom one it will still display "Joske"
This is because these tags
<div id="friendlist"><p><a>
Joske:
Offline</a></p><p><a>
Tom:
Offline</a></p><p><a>
Dirk:
Offline</a></p></div>
are not being formatted correctly, how can I make them format correctly?
As Shaunak D mentioned in a comment, you can use .trim() to remove preceding and trailing whitespace, including new lines, from text. You can either use this on your text content when creating the node, or use it in your search function to exclude new lines.
In document.createTextNode:
var friendText = document.createTextNode(
friendsXML[i].textContent.trim() + ":" + statusXML[i].textContent);
In $('#searchinfriend').keyup:
$('#searchinfriend').keyup(function () {
var valThis = $(this).val().toLowerCase();
$('#friendlist p a').each(function () {
var text = $(this).text().trim().toLowerCase();
(text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
});
});

case insensitive word boundaries with regExp

for some reason the gi modifier is behaving as case sensitive. Not sure what's going on, but maybe someone knows why this is. it works fine when the cases are the same. This JSFiddle will demonstrate my problem. Code below. Thanks.
javaScript:
var search_value = $('#search').val();
var search_regexp = new RegExp(search_value, "gi");
$('.searchable').each(function(){
var newText =(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
$(this).html(newText);
});
HTML:
<input id = "search" value = "Red">
<div class = "searchable">this should be red</div>
<div class = "searchable">this should be Red</div>
Correct Code is
var search_value = $('#search').val();
var search_regexp = new RegExp(search_value, "gi");
$('.searchable').each(function(){
// var newText =$(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
var newText =$(this).html().replace(search_regexp, function(matchRes) {
return "<span class = 'highlight'>" + matchRes + "</span>";
});
$(this).html(newText);
});
output
Fiddle
Issues with your code:-
First: search_regexp - You haven't used search_regexp anywhere in your code
Your Code
var newText =$(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
Second
You are using search_value to replace. It will make both Red and red to either Red or red after replace.
eg: if search_value is Red then your output will be
this should be Red
this should be Red
you should use matched result instead of search_value
Third: How to use RegExp with replace function?
Correct Method is
var newText =$(this).html().replace(search_regexp, function(matchRes) {
return "<span class = 'highlight'>" + matchRes + "</span>";
});
Explanation
replace(<RegEx>, handler)
Your code isn't using your regex in the replace call, it's just using the search_value. This JSBin shows your code working: http://jsbin.com/toquz/1/
Do you actually want to replace the matches with the value (changing lowercase instances to uppercase in this example)? Using $.html() will also get you any markup within that element, so keep that in mind as well (in case there's a chance of having markup in the .searchable elements along with text.
Might be easier to do:
function highlight(term) {
var search_regexp = new RegExp(term, "gi");
$('.searchable').each(function(){
if (search_regexp.test($(this).html())) {
var highlighted = $(this).html().replace(search_regexp, function(m) {
return '<span class="highlight">'+m+'</span>';
});
$(this).html(highlighted);
}
});
}
Your original code in the JSBin is the highlightReplace() function.

JavaScript Failing in iWeb

I am using iWeb for some simple webpage development, and I have put some JavaScript in an HTML widget. The first widget I did worked perfectly, but the second one I am having issues with. The script is supposed to pull the $_GET variables from the URL to address the user. My script worked perfectly outside of iWeb, but fails what I copy it into an iWeb widget. Here is my code:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
//Replace all String Function
String.prototype.replaceAll = function(search, replace){
//if replace is null, return original string otherwise it will
//replace search string with 'undefined'.
if(!replace)
return this;
return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};
//GET from URL
var getVars = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i){
var tmp = args[i].split(/=/);
if(tmp[0] != ""){
getVars[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replaceAll("+", " "));
}
}
$(document).ready(function(){
$("#rsvpName").html(getVars["rsvpName"]);
if( getVars["rsvpResponse"] == "1" )
$("#rvspMessage").html( "You will be attending as part of a party of " + getVars["rsvpNum"] + "." );
else if( getVars["rsvpResponse"] == "0" )
$("#rvspMessage").html("We regret you will not be able to attend!");
alert( getVars["rsvpName"] + getVars["rsvpResponse"] + getVars["rsvpNum"]);
});
</script>
<h1>Thank you, <b><span id="rsvpName">Name</span></b>, for RSVPing.</h1>
<p id="rvspMessage">Message</p>
Anyone have a suggestion?

Selecting textareas within div tags

feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.

Categories

Resources