.getSelection() - javascript

HTML code--
<script language="javascript" type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.field.selection.js"></script>
<div id="copy">Copy</div>
<textarea....id="t">
jquery---
$(docu.....
$('#copy').click(function(){
var range = $('#TextArea').getSelection();
alert(range.text);
});
});
When the #copy button is pressed the alert does not show the selected text in #t. It comes in blank.
I need the selected text from the textarea

Your code is not running because, this statement fails
var range = $('#TextArea').getSelection();
There is nothing as TextArea as ID in the markup you provided, so the script encounters an error and does not continue beyond it.
If you place the alert at the top part, I am sure the alert box will pop up.
i.e
$('#copy').click(function(){
alert(''); //this will work
var range = $('#TextArea').getSelection();
alert(range.text);
});

getSelection is a method of the document, so you should do:
var range = document.getSelection();
also note that you'll have to use document.selection.createRange() in IE so everything gets a bit complicated.
take a look at this example for more information. you'll end up needing a function like this:
function getSelectedText(){
if(document.all){
var selection = document.selection;
var newRng = selection.createRange();
newRng.select();
return newRng.htmlText;
}else{
return document.getSelection();
}
}
wich should return the selected text and work in all major browsers.
EDIT:
just saw you're using some kind of jquery-plugin that (maybe) should make your code work. the problem is:
in your html, the id of the textarea is "t":
<textarea....id="t">
but in your javascript, you're trying to get the selection of id "TextArea":
$('#TextArea').getSelection();
please change the id of your textarea to "TextArea" (or the other way around) and see what happens.

I'm not sure about the question, but if you need to get the textarea value, just use the val jQuery method:
http://api.jquery.com/val/
$('#copy').click(function(){
var range = $('#t').val();
alert(range);
});

Either you change your id="t" or you change #TextArea to #t to get the textarea you have in your html markup.
But I have no idea what plugin that you are using or what it want.

Related

Editing a text in javascript with the result of a dropdown value

I made a piece of code from what I could find on the internet to display in a field, the value selected from a dropdown list with this code.
<input type="text" id="text">
<script type="text/javascript">
function update() {
var select = document.getElementById('list-category');
var option = select.options[select.selectedIndex];
document.getElementById('text').value = option.text;
}
update();
</script>
This one works very well but the problem is that the text is displayed in an <input>. It's not very aesthetic and above all, you can have fun modifying it. Do you know how I could make the text display simply? Without necessarily putting it in an <input> ? I have try with console.writebut I don't know the args to pass. Thanks for the help.
Instead of using the <input> tag, you can use the <span> tag. You can update its value with innerHtml property.

Removing everything after first word JS

The title is a little bland but my problem is explained below.
At the moment I currently have a live search:
This does what I want it to do, but of course, that's only possible with a little bit of JS.
Now when you click one of the options it gives you from your search it'd usually take you to a link, but I added the below JS so that it removes all HTML code from it and it appends the selected username from the drop down into a text box.
<script type="text/javascript">
$(document).ready(function(){
$("#livesearch").click(function(){
var value = $(this).html();
var input = $('#append_value');
var content = value;
var text = $(content).text(); //removes all HTML
input.val(text);
});
});
</script>
Now, this is all perfect and everything but there's a problem. When you select one option from the drop down it appends both options to the text box:
Now, this may have something to do with the code above, but I just want whichever option the user has selected to be appended to the text box.
So, for example, I search for the battlefield and I get a result of battlefield1 and battlefield2. If the user selected battlefield2 I want battlefield2 to be placed in the textbox, and vice versa.
I've been trying to do this since 1pm EST so you can trust me when I say I've looked plenty of times for a solution.
Thank you in advance for your help. :)
Edit:
What I'm doing the search with (yes I realize SQL is deprecated):
index.html
<script type="text/javascript">
function lightbg_clr() {
$('#qu').val("");
$('#textbox-clr').text("");
$('#search-layer').css({"width":"auto","height":"auto"});
$('#livesearch').css({"display":"none"});
$("#qu").focus();
};
function fx(str) {
var s1=document.getElementById("qu").value;
var xmlhttps;
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
document.getElementById("livesearch").style.display="block";
$('#textbox-clr').text("");
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttps=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttps=new ActiveXObject("Microsoft.XMLHTTPS");
}
xmlhttps.onreadystatechange=function() {
if (xmlhttps.readyState==4 && xmlhttps.status==200) {
document.getElementById("livesearch").innerHTML=xmlhttps.responseText;
document.getElementById("livesearch").style.display="block";
$('#textbox-clr').text("X");
}
}
xmlhttps.open("GET","scripts/search_friends.php?n="+s1,true);
xmlhttps.send();
}
</script>
<input type="text" onKeyUp="fx(this.value)" autocomplete="off" name="qu" id="qu" class="form-control" placeholder="Name of the person or group">
<div class="list-group" id="livesearch"></div>
<input type="text" id="append_valueq">
<script type="text/javascript">
$(document).ready(function(){
$("#livesearch").click(function(){
var value = $(this).val();
var input = $('#append_valueq');
var content = value;
var text = $(content).text();
input.val(text);
});
});
</script>
search_friends.php
<?php
include('../Connections/ls.php'); //script to connect to DB
$s1=$_REQUEST["n"];
$select_query="SELECT * FROM users WHERE Username LIKE '%".$s1."%'";
$sql=mysql_query($select_query) or die (mysql_error());
$s="";
while($row=mysql_fetch_array($sql))
{
$s=$s."
<a href='javascript:void(0)'>".$row['Username']."</a>
" ;
}
echo $s;
?>
This ultimately gives me the result you see in the first image.
I'm realizing now that the problem I'm having is the fact that div has an id of livesearch (<div class="list-group" id="livesearch"></div>), so it's selecting the whole div instead of the actual options in the dropdown...
Try using .val() instead of html() while fetching the value.
There is actually a really simple way to do this.
Since you haven't provided your HTML code, I'll show what I would have done.
You can get the value of the click with:
document.getElementById("dropdown").value();
Make sure you don't include the hashtag/pound sign in the id.
Then, you can apply this value, let's say you call it val, this way:
document.getElementById("textbox").value = val
I've created a JSFiddle that kind-of shows the concept. See if you can get it to work with your own code: https://jsfiddle.net/1j4m1ekc/7/
If the problem persists, just let me know. I'd also like to see your html.
I don't need a solution right away for this as I've found another alternative to do what I want to do, but it would be greatly appreciated in case someone else from the Stackoverflow community has a question similar to this and need a solution. The solution I found is below.
This is still considered a live search but, I created a scrollable container and listed all of the users in that container, so it now looks like this.
Now from that container I found a script online that will filter out any and all users that do not match the input from the search box. The script I found is from here: Live Search and if you want to take a look at a demo as to how the script works, View Demo. So now when I enter a search term into the text box it looks like this
This may not be the greatest solution but it works for me and does what I want it to do. Maybe it'll work for you as well :)

Auto fitting text in a textbox

Can't seem to find out to do this in either html or JS (or maybe even jquery?).
I have a text-box that echo's whatever is typed into it in an input box more down the page. This echo box needs to auto-fit to whatever text is inside it so that it doesn't have this huge white space spot after the text.
Any ideas how to auto-fit a input field to text that is inserted into it?
I think you're looking for something like this: http://jsfiddle.net/ener3/
$("#in").keyup(function(){
var tmp = $("<span>")
.text(this.value)
.css("font", $("#out").css("font"))
.appendTo("body"),
wid = tmp.width();
tmp.remove();
$("#out").val(this.value).width(wid);
});
where #in is the id of the input, and #out is the textbox you want to autosize.
You can add this to the head of the page like so:
<script type="text/javascript">
$(function(){
// paste the above code here
});
</script>
Make sure you put the script tag after your jQuery include:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
You can replace 1.8.3 with the version of jQuery you want to target. I wouldn't recommend using jQuery-latest to start as you'd have to account for potential deprecation where applicable.

How to append text to '<textarea>'?

I have <textarea> where user can type in his message to the world! Below, there are upload buttons... I would love to add link to uploaded file (don't worry, I have it); right next to the text that he was typing in.
Like, he types in 'Hello, world!', then uploads the file (its done via AJAX), and the link to that file is added in next line to the content of <textarea>. Attention! Is it possible to keep cursor (place where he left to type) in the same place?
All that may be done with jQuery... Any ideas? I know that there are method 'append()', but it won't be for this situation, right?
Try
var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');
This took me a while, but the following jQuery will do exactly what you want -- it not only appends text, but also keeps the cursor in the exact same spot by storing it and then resetting it:
var selectionStart = $('#your_textarea')[0].selectionStart;
var selectionEnd = $('#your_textarea')[0].selectionEnd;
$('#your_textarea').val($('#your_textarea').val() + 'The text you want to append');
$('#your_textarea')[0].selectionStart = selectionStart;
$('#your_textarea')[0].selectionEnd = selectionEnd;
You should probably wrap this in a function though.
You may take a look at the following answer which presents a nice plugin for inserting text at the caret position in a <textarea>.
You can use any of the available caret plugins for jQuery and basically:
Store the current caret position
Append the text to the textarea
Use the plugin to replace the caret position
If you want an "append" function in jQuery, one is easy enough to make:
(function($){
$.fn.extend({
valAppend: function(text){
return this.each(function(i,e){
var $e = $(e);
$e.val($e.val() + text);
});
}
});
})(jQuery);
Then you can use it by making a call to .valAppend(), referencing the input field(s).
You could use my Rangy inputs jQuery plugin for this, which works in all major browsers.
var $textarea = $("your_textarea_id");
var sel = $textarea.getSelection();
$textarea.insertText("\nSome text", sel.end).setSelection(sel.start, sel.end);

How to change a label's contents using Javascript?

I have a label that holds a value and a text box into which I will enter a number. I have another label, which should dynamically give the difference between the two as I type the number in the text box. How do I do this using Javascript? I tried:
<script type="text/javascript">
function compute_diff(){
var lbl1 = document.getElementById("<%=label1.ClientID%>").value;
var txtbox = document.getElementById("<%=textbox1.ClientID%>").value;
var lbl2value = lbl1 - txtbox
document.getElementById("<%=label2.ClientID%>").innerText = lbl2value;
return true;
}
</script>
I am calling this function on the OnKeyUp event, but it is not firing it. What is the correct way of going about this? I am developing the site using ASP.Net.
The line
var lbl2value = lbl1 - txtbox
will not work. You will need to use a string diff algorithm such as the one at
http://ejohn.org/projects/javascript-diff-algorithm/
In addition, consider using jQuery to ensure that this works cross browser as the implementation of innerText can differ from browser to browser.

Categories

Resources