How to use getSelection with an iframe - javascript

I have been trying use the getSelection command to select highlighted text from an iframe and insert it into a variable. Using the follow code I could make this work a textarea.
<script type="text/javascript">
function GetSelectedText () {
var selText = "";
if (window.getSelection) {
if (document.activeElement &&
(document.activeElement.tagName.toLowerCase () == "textarea" ))
{
var text = document.activeElement.value;
selText = text.substring (document.activeElement.selectionStart,
document.activeElement.selectionEnd);
}
else {
var selRange = window.getSelection ();
selText = selRange.toString ();
}
}
else {
if (document.selection.createRange) {
var range = document.selection.createRange ();
selText = range.text;
}
}
var highlight = selText;
if (highlight !== "") {
alert (highlight);
}
if (highlight == "") {
alert ("No string selected");
}
} </script>
<body >
<br /><br />
<textarea onclick="GetSelectedText ()">Some text in a textarea element.</textarea>
</body>
But when I add the following line of code, it still won't execute in an iframe.
|| document.activeElement.tagName.toLowerCase () == "iframe"
How can I fix this so I can highlight a string from my iframe and have the script execute?
UPDATED:
<script type="text/javascript">
var editorDoc;
function InitEditable () {
var editor = document.getElementById ("editor");
if (editor.contentDocument)
editorDoc = editor.contentDocument;
else
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.body;
if ('contentEditable' in editorBody) {
// allow contentEditable
editorBody.contentEditable = true;
}
else { // Firefox earlier than version 3
if ('designMode' in editorDoc) {
// turn on designMode
editorDoc.designMode = "on";
}
}
}
var iframe = document.getElementById('editor');
var innerDoc = iframe.contentDocument;
function GetSelectedText () {
var selText = "";
if (innerDoc.getSelection) {
if (innerDoc.activeElement &&
(innerDoc.activeElement.tagName.toLowerCase () == "iframe"))
{
var text = innerDoc.activeElement.value;
selText = text.substring (innerDoc.activeElement.selectionStart,
innerDoc.activeElement.selectionEnd);
}
else {
var selRange = innerDoc.getSelection ();
selText = selRange.toString ();
}
}
else if
(innerDoc.selection.createRange) {
var range = innerDoc.selection.createRange ();
selText = range.text;
}
var highlight = selText;
if (highlight !== "") {
alert (highlight);
}
if (highlight == "") {
alert ("No string selected");
}
}
</script>
<body onload="InitEditable ();">
<iframe onclick="GetSelectedText ()" id="editor"></iframe>
</body>

It sounds like the script runs in the iframe's parent window. As such, you will need to use a different object than document to access it:
var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument;

Related

In Swashbuckle / Swagger; How do I hide a dropdown menu based on anothers selected value

I'm struggeling with this functionality of hiding a row based on a select:
<tr data-param-name="nodeGroup">
in web api, Program.cs:
app.UseSwaggerUI(options => {
options.InjectJavascript("/custom.js");
});
The javascript custom.js:
var providerSelect = null;
var nodeGroup = null;
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
// document ready
providerSelect = document.querySelector("[data-param-name='provider'] select");
nodeGroup = document.querySelector("[data-param-name='nodeGroup']");
if (providerSelect) {
providerSelect.addEventListener("change", function () {
var text = providerSelect.options[providerSelect.selectedIndex].text;
if (text == "EcoPlatform") {
nodeGroup.setAttribute("visibility", "visible");
}
else {
nodeGroup.setAttribute("visibility", "collapse");
}
});
}
}
};
The above does not work.
The page is not actually shown on readystate === 'complete'
providerSelect does not get populated before I click the downarrow on the "accordion". <noscript> is replaced on click.
Was solved like this:
document.addEventListener("change", function (event) {
var providerSelect = document.querySelector("[data-param-name='provider'] select");
if (event.target == providerSelect) {
var nodeGroup = document.querySelector("[data-param-name='nodeGroup']");
var selectedText = providerSelect.options[providerSelect.selectedIndex].text;
var dataset = document.querySelector("[data-param-name='datasetType']");
if (selectedText == "EcoPlatform") {
nodeGroup.style["visibility"] = "visible";
dataset.style["visibility"] = "visible";
}
else {
nodeGroup.style["visibility"] = "collapse";
dataset.style["visibility"] = "collapse";
}
}
});

HTML button that's submitting an empty field even though it shouldn't be

Here's the HTML button I'm working with:
<b>Other: </b><input type="number" id="AmntValue" data-target-element-id="SubmitAmnt" data-target-parameter="Amnt" onchange="setValueOnTarget(this);' +/* ' enableButton(SubmitAmnt);' */+ '">
<button class="button2" id="SubmitAmnt" type="button" data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount=" onclick="disableButton(this); addValueToQueryString(this); redirectPage(this);">Continue To Payment</button>
When someone hits the button but the "Other" text field is blank, it's supposed to not redirect and instead show an error message. Right now the error message displays, but only for a quick moment before it redirects anyway.
Here is my complete JavaScript code:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem)
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
function displaySuccess(message) {
var userMessage = document.getElementById('userMessage1');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'green';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
I'm not sure if something's wrong with the code I put in the button or in the JavaScript.
Disable button by default
The button should be disabled by default, and should only be enabled when the expected input value is detected. It appears you already have a mechanism for this in your example, but you have some impediments to overcome first:
button should be disabled by default. Do this in the HTML:<button disabled …>Continue To Payment</button>
input's onchange handler should just call setValueOnTarget(), because this function already calls EnableButton(). In the HTML:<input onchange="setValueOnTarget(this);" … >
Remove the call to redirectPage() from the button's onclick handler and move it into addValueToQueryString() after you have assigned a value to newSrc.
Add a call to EnableButton() after you call displayError() in cases where you want to allow the user to modify the input and try again.
For example:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
console.log(targetElem);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem);
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
redirectPage(elem);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
EnableButton(elem);
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
<b>Other: </b>
<input
type="number"
id="AmntValue"
data-target-element-id="SubmitAmnt"
data-target-parameter="Amnt"
onchange="setValueOnTarget(this);">
<button
disabled
class="button2"
id="SubmitAmnt"
type="button"
data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount="
onclick="disableButton(this); addValueToQueryString(this);">Continue To Payment</button>
<div id="userMessage"></div>

Get caret HTML position in contenteditable DIV

I am having troubles figuring out how to get caret position in a DIV container that contains HTML tags.
I am using this JavaScript function to do that:
function getCaretPosition()
{
if (window.getSelection && window.getSelection().getRangeAt)
{
var range = window.getSelection().getRangeAt(0);
var selectedObj = window.getSelection();
var rangeCount = 0;
var childNodes = selectedObj.anchorNode.parentNode.childNodes;
for (var i = 0; i < childNodes.length; i++)
{
if (childNodes[i] == selectedObj.anchorNode)
{
break;
}
if(childNodes[i].outerHTML)
{
rangeCount += childNodes[i].outerHTML.length;
}
else if(childNodes[i].nodeType == 3)
{
rangeCount += childNodes[i].textContent.length;
}
}
return range.startOffset + rangeCount;
}
return -1;
}
However, it finds a caret position of the text in my DIV container, when I need to find the caret position including HTML tags.
For example:
<DIV class="peCont" contenteditable="true">Text goes here along with <b>some <i>HTML</i> tags</b>.</DIV>;
(please note, that HTML tags are normal tags and are not displayed on the screen when the function is returning caret position)
If I click right between H and TML, the aforementioned function will find caret position without any problems. But I am getting the contents of DIV box in HTML format (including all tags), and if I want to insert something at that caret's position, I will be off by a few or many characters.
I went through many posts, but all I could find is either <TEXTAREA> caret postions, or functions similar to what I have posted. So far I still cannot find a solution to get a caret position in a text that has HTML formatting.
Can anyone help, please?
PS. Here's JQuery/Javascript code that I wrote for the link button:
$('#pageEditor').on('click', '.linkURL', function()
{
var cursorPosition;
cursorPosition = getCaretPosition();
var contentID = $(this).parent().parent().attr('id');
var userSelected = getSelectionHtml();
var checkLink = userSelected.search('</a>');
var anchorTag = 0;
if(checkLink == -1)
{
var currentContents = $('#'+contentID+' .peCont').html();
var indexOfSelection = currentContents.indexOf(userSelected);
var getPossibleAnchor = currentContents.slice(indexOfSelection, indexOfSelection+userSelected.length+6);
anchorTag = getPossibleAnchor.search('</a>');
}
if(checkLink > 0 || anchorTag > 0)
{
//alert(checkLink);
document.execCommand('unlink', false, false);
}
else
{
$('#'+contentID+' .peCont').append('<div id="linkEntry"><label for="urlLink">Please enter URL for the link:<label><input type="text" id="urlLink" /></div>');
$('#linkEntry').dialog({
buttons: {
"Ok": function()
{
var attribute = $('#urlLink').val();
var newContentWithLink = '';
if(attribute != '')
{
if(userSelected != '')
{
var currentContent = $('#'+contentID+' .peCont').html();
var replacement = ''+userSelected+'';
newContentWithLink = currentContent.replace(userSelected, replacement);
}
else
{
var currentTextContent = $('#'+contentID+' .peCont').html();
var userLink = ''+attribute+'';
if(cursorPosition > 0)
{
var contentBegin = currentTextContent.slice(0,cursorPosition);
var contentEnd = currentTextContent.slice(cursorPosition,currentTextContent.length);
newContentWithLink = contentBegin+userLink+contentEnd;
}
else
{
newContentWithLink = attribute+currentTextContent;
}
}
$('#'+contentID+' .peCont').empty();
$('#'+contentID+' .peCont').html(newContentWithLink);
}
$(this).dialog("close");
} },
closeOnEscape:true,
modal:true,
resizable:false,
show: { effect: 'drop', direction: "up" },
hide: { effect: 'drop', direction: "down" },
width:460,
closeText:'hide',
close: function()
{
$(this).remove();
}
});
$('#linkEntry').on('keypress', function(urlEnter)
{
if(urlEnter.which == 13)
{
var attribute = $('#urlLink').val();
var newContentWithLink = '';
if(userSelected != '')
{
var currentContent = $('#'+contentID+' .peCont').html();
var replacement = ''+userSelected+'';
newContentWithLink = currentContent.replace(userSelected, replacement);
}
else
{
var currentTextContent = $('#'+contentID+' .peCont').html();
var userLink = ''+attribute+'';
if(cursorPosition > 0)
{
var contentBegin = currentTextContent.slice(0,cursorPosition);
var contentEnd = currentTextContent.slice(cursorPosition,currentTextContent.length);
newContentWithLink = contentBegin+userLink+contentEnd;
}
else
{
newContentWithLink = attribute+currentTextContent;
}
}
$('#'+contentID+' .peCont').empty();
$('#'+contentID+' .peCont').html(newContentWithLink);
$(this).dialog("close");
}
});
}
});
I created a simple fiddle for you that does what you want.
This should work in recent versions of Firefox, Chrome and Safari.
It's your homework to add Opera and IE support if you need.

integrating two javascripts codes into one code to show alerts

In my first javascript i am showing alerts if any text box having class check is left empty before submitting, if all are filled then in second javascript i am showing an alert that confirm submit?. But how to make these two as one javascript code?
<script type="text/javascript">
jQuery('input.test').not('[value]').each(function() {
var blankInput = jQuery(this);
//do what you want with your input
});
function confirmation(domForm) {
var jForm = jQuery(domForm);
var jFields = jForm.find('.check');;
var values = jFields.serializeArray();
var failedFields = [];
for(var i = 0; i < values.length; i++) {
var o = values[i];
if(o.value == null || o.value.length == 0) {
failedFields.push(jFields.filter('[name=' + o.name + ']').attr('title'));
}
}
if(failedFields.length > 0) {
var message = '';
if(failedFields.length == values.length) {
message = 'fill all fields please';
}
else {
message = 'please fill the fields:';
for(var i = 0; i < failedFields.length; i++) {
message += "\n";
message += failedFields[i];
}
}
csscody.alert(message);
return false;
}
var answer = confirm("Confirm save?")
if (answer){
window.location = "confirmsubmit.jsp";
}
else{
return false;
}
return true;
}
</script>
javascript to show confirm submit alert after text boxes having class check are filled
<script type="text/javascript">
$().ready(function() {
$('#btn_submit').click(function(e) {
e.preventDefault();
var that = this;
var text = "Confirm save?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
window.location = "confirmsubmit.jsp";
}
else {
return false;
}
}
})
});
});
</script>
html
<form action="confirmsubmit.jsp" onsubmit="return confirmation(this)" method="POST">
<input type="text" class="check"/>//alert if text box is left empty
<input type="submit" id="btn_submit"/>
</form>
I don't get why you need the second script. You call the validator function onsubmit. Why do change the window.location when you have set the same action? There is not point in binding the same function the the click-event of the button.
You don't need the second script, but have to change the first script.
function confirmation(domForm) {
// Your other code
// ...
if(failedFields.length > 0) {
// Your other code
// ...
csscody.alert(message);
return false;
}
// Your other code
// ...
/* Solution before your comment:
var answer = confirm("Confirm save?")
// This is already the action-target: window.location = "confirmsubmit.jsp";
return answer;
*/
var text = "Confirm save?";
csscody.confirm(text, {
onComplete: function(e) {
if (e) {
// Probably doesn't work because this seems to be asynchronous?
return true;
}
else {
return false;
}
}
});
}

About javascript showbox,I need some help! online~~

<div id="wrapper">
<button id="ppp">button</button>
<div id="content" style="display:none;"></div>
</div>​
if i click the button,the content will be show(open),
if the content is on show(open),when i click document(except the content),the content will be close.
var $ = function (id){
return !id ? null : document.getElementById(id);
}
var addEventSimple = function(obj, evt, fn) {
if (obj.addEventListener){ // W3C
obj.addEventListener(evt, fn, false);
}else if (obj.attachEvent) // Microsoft
obj.attachEvent('on' + evt, fn);
}
var button = $('ppp'),
content = $('content');
var init = function() {};
init.handleObj = button;
init.showbox = content;
init.flag = false;
init.allowcls = false;
init.open = function () {//open the content
if (this.flag == false) {
this.showbox.style.display = "block";
this.flag = true;
this.allowcls = true;
}
};
init.close = function () { // close the content
if (this.flag && this.allowcls) {
this.showbox.style.display = "none";
this.flag = false;
this.allowcls = false;
}
};
init.load = function() { // button click
//e = e ||window.event;
//e.preventDefault();
if (this.flag) {
this.close();
} else {
this.open();
}
};
init.clickClose = function(e) { // document click
if (!this.allowcls) {
return;
}
e = e ||window.event;
var target = e.target;
if (target === this.showbox) { // button
return;
}
this.close();
};
addEventSimple(button, 'click', function (){
init.load();//the code run here OK
})// error on here,but i don't know why?
addEventSimple(document, 'click', function (e){
init.clickClose(e);
})
code in here :http://jsfiddle.net/DCty3/
To toggle element display, you can use function like this:
function toggleDisplay(id) {
var elem = document.getElementById(id);
elem.style.display = (elem.style.display != 'none' ? 'none' : '');
}
There is unlimited id toggle script too:
function toggle() {
for ( var i=0; i < arguments.length; i++ ) {
var elem = document.getElementById(id);
elem.style.display = (elem.style.display != 'none' ? 'none' : '' );
}
}
With jQuery it will be just:
function toggleDisplay(id) {
$('#' + id).toggle();
}
I like getting fancy with objects, here is another multifunctional method:
var display = {
show : function() {
for ( i=0; i < arguments.length; i++ ) {
document.getElementById(arguments[i]).style.display = '';
}
},
hide : function() {
for ( i=0; i < arguments.length; i++ ) {
document.getElementById(arguments[i]).style.display = 'none';
}
},
toggle : function() {
for ( i=0; i < arguments.length; i++ ) {
var elem = document.getElementById(arguments[i]);
elem.style.display = (elem.style.display != 'none' ? 'none' : '' );
}
}
};
To use it, do something like this:
display.show('content','content2','content3');
display.hide('content','content2','content3');
display.toggle('content','content2','content3');
For convenience, you can add another function to enable button:
function toggleDisplayButton(bId, cId) {
document.getElementById(bId).onclick = (function() {
toggleDisplay(cId);
});
}
window.onload = (function() {
toggleDisplayButton('ppp','content');
});
To enable function, when user clicks "outside" the box, and it closes, there is used an easy trick, by creating another element in background, that covers all area around:
<div id="wrapper">
<button id="ppp">button</button>
<div id="outerBox" style="display:none;"></div>
<div id="content" style="display:none;">1</div>
</div>
CSS should make your container relative positioned and "trick box", absolutely positioned, with maximum size of screen, and z-indexed under container like this:
#content{width:100px;height:100px;background-color:#efefef;border:1px solid #555555;z-index:56;position:relative;}
#outerBox{width:100%;height:100%;position:absolute;top:0;left:0;z-index:55;}
And make it work like this:
var display = {
toggle : function() {
for ( i=0; i < arguments.length; i++ ) {
var elem = document.getElementById(arguments[i]);
elem.style.display = (elem.style.display != 'none' ? 'none' : '' );
}
}
};
function toggleBox() {
document.getElementById('ppp').onclick = (function() {
display.toggle('content','outerBox');
});
document.getElementById('outerBox').onclick = (function() {
display.toggle('content','outerBox');
});
}
onload = function() {
toggleBox();
}
The result looks like this.
Your question is exactly same as this one:-
Check out this post :-
jQuery on click $(document) - get clicked element
Hope this will help.

Categories

Resources