Jquery text input acting funny - javascript

I have the following jQuery to modify a table cell when clicked -- it will enable a user to fill out a text input and on enter, return to the normal <td>.
HTML-
<td class="delivered">
{{ title.delivery_date|date:"Y-m-d" }}
</td>
JS -
$("td.delivered").click(function () {
if ($(this).find('#inp').length == 0) {
var before = $(this).text();
var title_id = $(this).parent().attr('id');
var status_type = 'delivery-date'
$(this).html($("<input/>", {
id: 'inp',
style: 'width:70px;',
placeholder: 'YYYY-MM-DD',
change: function () {
selectdone(this, title_id, status_type);
}
}));
$("#inp").focus();
$('#inp').val(before);
}
});
The above js works, but there is a quirk about it.
Even though the input element is 70px, it seems to scroll as if the text width were 200px or so. This makes it so that you are unable to see the placeholder after first clicking the td. How would I make it such that that the cursor is always flush left and the text input is 70px in every which way.
Update: This is what the input looks like after entering text and sending it via POST: u'status': [u'\t\t\t\t\t\t\t\t\t\t\t2012-01-01']. In other words, it seems to be starting with 11 tabs in the text input! Why does this occur and how would I get rid of this?

You could wrap your input box in a div with width:70px;overflow:hidden so you're sure that you won't see any scrollbars.

Related

jQuery highlight plugin cancels text selection, making copy impossible while also rendering links unclickable

I'm using the jQuery Highlight plugin to select some text on a web page.
I've hooked up selecting and deselecting with mouse events:
document.addEventListener('mouseup', doSelect);
document.addEventListener('mousedown', doDeselect);
The functions are:
function doSelect() {
var selectionRange = window.getSelection();
var selection = selectionRange.toString();
if (selection.trim().length > 0) {
$('body').highlight(selection);
}
}
function doDeselect() {
$('body').unhighlight();
}
Short and easy. The library searches for the selected text and wraps each occurrence in a <span> and so the text stands out.
It's working great, but I have two issues with how it behaves.
The problem is that once the span elements are applied, I cannot click hyperlinks (the ones that were found/selected), they don't react to clicks (I have to deselect the text first).
Once the span elements are added, the original selection is somehow lost, i.e. I cannot copy what I selected with CTRL+C.
These issues can be seen in this jsfiddle.
Why is this happening?
The code
The working demo is available here: jsfiddle
JavaScript
var $body = $('body');
var $copyArea = $('#copyArea');
document.addEventListener('mouseup', doSelect);
document.addEventListener('mousedown', doDeselect);
document.addEventListener('keydown', keyPressHandler);
function keyPressHandler(e) {
if(e.ctrlKey && e.keyCode == 67) {
$copyArea.focus().select();
}
}
function doSelect() {
var selectionRange = window.getSelection();
var selection = selectionRange.toString();
if (selection.trim().length > 0) {
$copyArea.val(selection);
$body.highlight(selection);
}
}
function doDeselect(e) {
var elem = $(e.target).parents('a');
if(elem.length == 0) {
$copyArea.val('');
$body.unhighlight();
}
}
HTML
Sample text to select.
<br/>Sample text to select.
<br/>Sample text to select.
<br/>google.com
google.com
<a href="http://google.com" target="_blank">
<span>
<span>google.com</span>
</span>
</a>
<textarea id="copyArea"></textarea>
CSS
.highlight {
background-color: #FFFF88;
}
#copyArea {
position:fixed;
top:-999px;
height:0px;
}
Part 1 - Clicking through the selection
Presumably, the reason clicking on a highlighted link doesn't work is because the process that disables the highlighting kicks in first and cancels the click.
To bypass that, we implement a condition that checks if the target element of the mousedown event has an a element as ancestor. If that is true, we simply do not execute $body.unhighlight();, allowing the click to pass through and open the link.
function doDeselect(e) {
var elem = $(e.target).parents('a');
if(elem.length == 0) {
$copyArea.val('');
$body.unhighlight();
}
}
Part 2 - Copying the selection
Presumably, again, the reason the selection is lost is because the document is modified by the highlighting, which introduces elements into the DOM.
My first idea was to reapply the selection after the modification was done. This became annoying and I went in a different direction, which allowed me to stumble upon this:
The Definitive Guide to Copying and Pasting in JavaScript
This offered a simple and efficient idea: using an hidden element that could contain selectable text.
Therefore, to allow copying the selected text that we highlighted despite having lost the original selection:
We add a hidden textarea element to our document.
<textarea id="copyArea"></textarea>
We get a reference to that element.
var $copyArea = $('#copyArea');
We add an event handler for the keydown event.
document.addEventListener('keydown', keyPressHandler);
We add the event handler.
function keyPressHandler(e) {
if(e.ctrlKey && e.keyCode == 67) {
$copyArea.focus().select();
}
}
We modify doSelect() to add some logic that will set the selection as the value of the textarea element, in the form of $copyArea.val(selection);.
function doSelect() {
var selectionRange = window.getSelection();
var selection = selectionRange.toString();
if (selection.trim().length > 0) {
$copyArea.val(selection);
$body.highlight(selection);
}
}
What does the handler do ? it captures the combination CTRL+C and focuses on the text in the hidden textarea, which ends up being copied by the keyboard command we just issued.

Switch span text using JQuery in a table

I have a table generated from a program, listing info from a database. You can see it here:
http://www.homeducate.me/cgi-bin/browseTutors.cgi?Lui=en&countryCode=MO
For one piece of text, if it's long, I'm listing a shortened version of the text.
Now I'd like to switch it to the longer version when the user clicks on the row to expand some other rows below.
My table has a set of repeating sections like this:
<tr class="header">
//some stuff
<script>
var approachTxt1 = "Shortened version of the text...";
var approachFullTxt1 = "Full length version of the text to be displayed.";
</script>
<td><img src="an_image.png"><span id="approach1">Shortened version of the text...</span><img src="another_image.png"></td>
//some more stuff
</tr>
<tr>Some more rows of stuff</tr>
Then I use the following script to (1) initially collapse all the rows up under each header row, (2) toggle them to display again when a header row is clicked (3) redirect to a url if the user clicks on the un-hidden rows and (4) change the pointer to a mouse when over the table. It all works nicely.
<script>
$('#listTutors .header').each(function () {
$(this).nextUntil('tr.header').toggle();
});
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
});
});
$("tr:not('.header')").click(function () {
top.window.location.href="http://www.homeducate.me/cgi-bin/createAccountForm.cgi?Lui=en";
});
$('html,table').css('cursor','pointer');
</script>
Now what I wanna do is switch the shortened version of the text to the full text when the user clicks to expand that section, and then switch it back to the shortened form once again when the user clicks again to hide that section. I've been trying:
$(this).next('span').html($(this).next('span').html() == approachTxt1 ? approachFullTxt1 : approachTxt1);
But I'm getting "undefined is not a function" and "unexpected string" errors. Its clearly not picking up the span after the current header.
Plus I'm struggling to think how can I actuate this change for each set of my table rows (eg. switch the appropriate strings out according to which header row the user picks). I've been scratching my head on this for too long :( and would really appreciate any guidance.
Any help much appreciated.
Cheers.
Ok, finally worked out how to do it. Posting here just in case it might help someone else in the future....
First, I set a unique id for each section of my table:
<tr class="header" id="$nnn">
where $nnn is driven from my Perl program and is simply 1,2,3 etc.
Then for each section of the table, I put the short and long text strings into elements of an array:
<script>
approachTxt[$nnn] = "short version of the text";
approachFullTxt[$nnn] = "long version of the text which will be switched in and out";
</script>
Then my script becomes:
<script>
$('#listTutors .header').each(function () {
$(this).nextUntil('tr.header').toggle();
});
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
});
$('#span' + this.id).html($('#span' + this.id).html() == approachTxt[this.id] ? approachFullTxt[this.id] : approachTxt[this.id]);
});
$("tr:not('.header')").click(function () {
top.window.location.href="http://www.homeducate.me/cgi-bin/createAccountForm.cgi?Lui=en";
});
$('html,table').css('cursor','pointer');
</script>
Now it all works beautifully.
And I can sleep better tonight :)

Getting siblings value with javascript

I create a textarea and a button on a loop based on a certain condition:
while($row_c= mysqli_fetch_array($result_comments))
{
//some code goes here
<textarea type="text" id="pm_text" name="text"></textarea><br>
<button name="send_comment" id="post_comment" class="button" onClick="post_pm_comment()">Post</button>
}
Now in my function "post_pm_comment" I would like to access the text written in the textarea when the post button is clicked.
I tried this, but it only gives me the text of the first textarea and button created:
function post_pm_comment(thidid, pm_id, path, pm,getter)
{
var pm_text = document.getElementById("pm_text").value;
}
What should I do?
Thank you
Your code is outputting an invalid DOM structure, because id values must be unique on the page. You cannot have the same id on more than one element. Remove the id values entirely, you don't need them.
Having done that, the minimal-changes answer is to pass this into your handler:
onClick="post_pm_comment(this)"
...and then in your handler, do the navigation:
function post_pm_comment(postButton)
{
var pm_text;
var textarea = postButton.previousSibling;
while (textarea && textarea.nodeName.toUpperCase() !== "TEXTAREA") {
textarea = textarea.previousSibling;
}
if (textarea) {
pm_text = textarea.value; // Or you may want .innerHTML instead
// Do something with it
}
}
Live Example | Source

jQuery - Setting Hidden field to Textarea contents when Textarea name is Dynamic

I have a textarea in each row of my table. I need to set this textarea to the value of a hidden field associated with it.
The names of the textarea and hidden field look like so:
Textarea name:
sc-(Account Name)c
Hidden fields name:
sc-(Account Name)h
An example would be:
Textarea:
sc-usernamec
Hidden field:
sc-usernameh
On submit or while they type the text, I need the hidden field to be updating with what is typed in the textarea. I'm fairly new to jQuery and Javascript, and I'm wondering how I can either a) go through each textarea field setting its content in the associated hidden field or b) set the hidden field to the textarea as they type.
I'm not sure which option I should use, nor how I would go about programming something of this nature.
If the textarea in question is a normal textarea then you can try
$(function() {
$(":hidden[name^='sc']").each(function() { // all hidden starting with sc
var id = this.id.substring(0,this.id.length-1)+"c";
var hid = $(this);
$("#"+id).on("keyup",function() {
hid.val($(this).val());
});
});
});
Live Demo
All bets are of course off if the textarea is converted to an editor - then you need to read
jQuery and TinyMCE: textarea value doesn't submit
which means
$(function() {
$("#myForm").on("submit",function() {
$('#sc_texth').val(tinyMCE.get('sc_textc').getContent());
});
});
or for more
$(function() {
$("#myForm").on("submit",function() {
$(":hidden[name^='sc']").each(function() { // hidden and starts with sc
var textareaID = this.id.substring(0,this.id.length-1)+"c";
$(this).val(tinyMCE.get(textareaID).getContent());
});
});
Live Demo
I think this may help you.
<p><textarea name="sc-username" id="sc-username" ></textarea></p>
<p><textarea name="sc-usernameh" id="sc-usernameh" style="display:none;"></textarea></p>
$(document).ready(function(){
$("textarea").on("keyup",function() {
var name = $("#"+$(this).attr('name')+"h");
if(name)
name.val($(this).val());
});
});

When click change to text-area, When outside click change back

I am trying to make a function like PHPadmin what they are using on when showing the table, when click the div filed, change to text-area, and when click outside of the div, change it back to the div filed. The code below is wrong, I cannot change back to the div filed when I click outside. Please help me to improve the code.
JS:
$('#editor #gird_edit').bind({
click: function() {
$(this).html('<textarea id="gird_edit">'+$(this).text()+'</textarea>');
},
blur: function() {
$(this).html('<div id="gird_edit">'+$(this).text()+'</div>');
}
});
Html:
<div id='editor'>
<div id='gird_edit'>hallo world</div>
<div id='gird_edit'>hallo world 2</div>
<div id='gird_edit'>hallo world 3</div>
</div>
I only have 8 reputations, I cannot vote you back. However, I sincerely appreciate your helps!
check this jsbin i just made, if you need anything else i'm glad to help.
see jsfiddle
updated jsfiddle
when $(this).html(textarea) is done, div is already blur. so the onBlur didn't work
$('#editor #gird_edit').bind({
click: function() {
var tex = $(this).text();
var textarea = $('<textarea id="gird_edit">'+tex+'</textarea>');
$(this).html(textarea);
textarea.focus();
textarea.blur(function(){
var currentText = textarea.val();
if(currentText == tex)//not change
textarea.parent().text(tex);
else //changed
alert(currentText);
});
}
});
edit 3:
else{
textarea.parent().text(currentText);
//something else
}
find more jquery API
When you first click on the #gird_edit it is a div, so this is a div, and you can replace its contents to change things. However, when you blur away #gird_edit is a textarea, so if you change its contents you're not really changing what you want to change (your just changing the insides of your textarea).
What you want to change is the div that's around the textarea, ie. the "parent" of that textarea. In other words, try:
blur: function() {
$(this).parent().html('<div id="gird_edit">'+$(this).text()+'</div>');
}

Categories

Resources