How to take result text when text-overflow property is applied - javascript

I have a div with css property text-overflow : ellipsis to add ellipsis and show the text in a single line.
When I perform jquery .text() or .html(), I get the full string, but I need the exact text displaying in the div currently (not the full string).
Can some one guide me how to take the exact displaying string using jquery or JS?
Actual String = "abcdefghijklmnop"
Due to CSS, the div displays "abcd..."
My expected result (using jQuery or JS) "abcd..."

This is not possible without trying to mimic CSS and recreate the strings with the ellipsis using JS.
The reason for this is that CSS only manipulates what is displayed to the user, not the HTML source itself. You can verify this by checking the source code for your document. This means that when you use .text() or .html() you get the values from the DOM, rather than what is displayed via the CSS filter.
There are a couple of hacks that does a pretty good job, but it is still no guarantee that the JS correctly mimics how CSS renders the text.

If you know the number of values you need every time then you can just use JS Like for example if it was always 4 values that gets entered in than it would be like this,
JS Fiddle
form
<form action="" method="post">
<p>
<label for="txt">My txt: </albel>
<input type="text" id="myTxt"><br />
<input type="submit" id="submitButton" value="Send">
</P>
</form>
js
document.getElementById('submitButton').onclick = function() {
myVariable = document.getElementById("myTxt").value;
alert(myVariable.slice(0, 4));
};
No matter what is typed in to the textbox it will be sliced to the first 4 characters.

Related

How can I get value of checked JSF radiobutton using JS? [duplicate]

I am trying to implement jQuery with PrimeFaces and JSF components, but it's not working properly. When I tried to do the same with HTML tags it;s working properly.
Here is the code with HTML tags which works properly with jQuery:
<input type="checkbox" id="check2"></input>
<h:outputText value="Check the box, if your permanent address is as same as current address."></h:outputText>
<h:message for="checkbox" style="color:red" />
with
$("#check2").change(function() {
if ($("#check2").is(":checked")) {
$("#p2").hide();
} else {
$("#p2").show();
}
});
Here is the code with PrimeFaces/JSF which doesn't work properly with jQuery:
<p:selectManyCheckbox >
<f:selectItem itemLabel="1" value="one" id="rad" ></f:selectItem>
</p:selectManyCheckbox>
with
$("#rad").change(function() {
if ($("#rad:checked").val() == "one") {
$("#p2").hide();
} else {
$("#p2").show();
}
});
You should realize that jQuery works with the HTML DOM tree in the client side. jQuery doesn't work directly on JSF components as you've written in the JSF source code, but jQuery works directly with the HTML DOM tree which is generated by those JSF components. You need to open the page in webbrowser and rightclick and then View Source. You'll see that JSF prepends the ID of the generated HTML input elements with the IDs of all parent NamingContainer components (such as <h:form>, <h:dataTable>, etc) with : as default separator character. So for example
<h:form id="foo">
<p:selectManyCheckbox id="bar" />
...
will end up in generated HTML as
<form id="foo" name="foo">
<input type="checkbox" id="foo:bar" name="foo:bar" />
...
You need to select elements by exactly that ID instead. The : is however a special character in CSS identifiers representing a pseudo selector. To select an element with a : in the ID using CSS selectors in jQuery, you need to either escape it by backslash or to use the [id=...] attribute selector or just use the old getElementById():
var $element1 = $("#foo\\:bar");
// or
var $element2 = $("[id='foo:bar']");
// or
var $element3 = $(document.getElementById("foo:bar"));
If you see an autogenerated j_idXXX part in the ID where XXX represents an incremental number, then you must give the particular component a fixed ID, because the incremental number is dynamic and is subject to changes depending on component's physical position in the tree.
As an alternative, you can also just use a class name:
<x:someInputComponent styleClass="someClassName" />
which ends up in HTML as
<input type="..." class="someClassName" />
so that you can get it as
var $elements = $(".someClassName");
This allows for better abstraction and reusability. Surely those kind of elements are not unique. Only the main layout elements like header, menu, content and footer are really unique, but they are in turn usually not in a NamingContainer already.
As again another alternative, you could just pass the HTML DOM element itself into the function:
<x:someComponent onclick="someFunction(this)" />
function someFunction(element) {
var $element = $(element);
// ...
}
See also:
How can I know the id of a JSF component so I can use in Javascript
How to use JSF generated HTML element ID with colon ":" in CSS selectors?
By default, JSF generates unusable IDs, which are incompatible with the CSS part of web standards
Integrate JavaScript in JSF composite component, the clean way
You also can use the jQuery "Attribute Contains Selector" (here is the url http://api.jquery.com/attribute-contains-selector/)
For example If you have a
<p:spinner id="quantity" value="#{toBuyBean.quantityToAdd}" min="0"/>
and you want to do something on its object you can select it with
jQuery('input[id*="quantity"]')
and if you want to print its value you can do this
alert(jQuery('input[id*="quantity"]').val());
In order to know the real html tag of the element you can always look at the real html element (in this case spinner was translated into input) using firebug or ie developer tools or view source...
Daniel.
If you're using RichFaces you can check rich:jQuery comonent. It allows you to specify server side id for jQuery component. For example, you have component with specified server id, then you can apply any jQuery related stuff to in next way:
<rich:jQuery selector="#<server-side-component-id>" query="find('.some-child').removeProp('style')"/>
For more info, please check doumentation.
Hope it helps.
look this will help you when i select experience=Yes my dialoguebox which id is dlg3 is popup.and if value is No it will not open

How to disable HTML formatting using innerHTML?

I'd like to generate an input field that is able to "copy" it's value into another element (in my case paragraph).
All is working so far but I got massive problems when I try to input some text strings like ...
< b> text < /b> // without the space columns
multiple backslashes
... or other HTML attributes / tags...
because changing the innerHTML will format this text into HTML text. But I want to use plain text including these tags / special characters instead.
Input some HTML text<input oninput="out1.innerHTML=this.value" type="text" placeholder="input text">
<p id="out1"></p>
----------------------------------------------------------<br><br>
Change this text:
<input oninput="out2.innerHTML=this.value" type="text" value="<b>x</b> \\ %&">
<p id="out2"></p>
How can I disable HTML formatting in this specific case (to copy exact the same text into the paragraph element without styling) without using a textfield / a second input field instead?
I thought about using .html() with jQuery but there also must be some more efficient way using only javascript.
I think you should try using Node.textContent
Because as the docs are saying:
Element.innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. However, textContent often has better performance because the text is not parsed as HTML.
Input some HTML text<input oninput="out1.textContent=this.value" type="text" placeholder="input text">
<p id="out1"></p>
----------------------------------------------------------<br><br>
Change this text:
<input oninput="out2.textContent=this.value" type="text" value="<b>x</b> \\ %&">
<p id="out2"></p>
You want .innerText rather than .innerHtml. This references the rendered text node. innerHtml, on the other hand, sets HTML content here, not simply text nodes.

Unable to fetch DOM elements Value

I have loaded an HTML page and ran some javascript code on the console. Can any one explain me the behavior.
document.getElementById('tiers__0__.threshold1') gives me
<input id=​"tiers__0__.threshold1" type=​"text" class=​"field mandatory" data-name=​"tiers__0__.threshold1" data-domain=​"ANY" name=​"dynamicValues['tiers__0__.threshold1']​" value=​"5" maxlength readonly>​
document.getElementById('tiers__0__.threshold1').value gives me
""
document.getElementById('tiers__1__.threshold1') gives me
<input id=​"tiers__1__.threshold1" type=​"text" class=​"field " data-name=​"tiers__1__.threshold1" data-domain=​"ANY" name=​"dynamicValues['tiers__1__.threshold1']​" value=​"10" maxlength readonly>​
document.getElementById('tiers__1__.threshold1').value gives me
"10"
Why is the 1st DOM element not giving me the value. Both the DOM elements have same structure. I generate them using Handlebars "each" property.
P.S. I know sometimes the DOT in an id creates issue. Even tried using escape sequence (//). Nothing worked. Tried Jquery also
$('#tiers__0__\\.threshold1').val() (Used double slash. SO just displays 1) gives me
""
Question Updated after more research.
The earlier test was done on Chrome browser but after doing it on Firefox got different result.
$('#tiers__0__.threshold1')
Object[input#tiers__0__.threshold1.field property value = "" attribute value = "5"]
Can anyone explain what is property value and why it it getting appended only for my 1st text box as null. Is their any way i can make this same as my attribute value or i can remove it completely.
Note -: I am using handlebar template for rendering a JSON object. I have checked both the JSON and Handlebar consists of uniform data. i have a input tag which looks like this
<input id="{{name}}{{#if count}}{{count}}{{/if}}" type="text" class="field {{#if this.mandatory}} mandatory{{/if}}" data-name="{{name}}" data-domain="{{domain}}" name="{{bindingName}}" value={{val}} maxlength="{{this.maxLength}}" {{#if this.locked}}readOnly{{/if}}/>
It renders perfect for other values in the for loop,only screws the 1st one with an extra property

How do I fill a javascript editor?

I use TEmbeddedWebBrowser to fill a html form using FillForm method. But my html form contains a fully javascript based editor and i don't know how to fill that.
Something like this :
your comment :
<script type='text/javascript' src='public/scripts/src/editor.js?1'></script>
And the submit btton :
<input type="submit" name="btnSubmit" id="btnSubmit" value="Send" class="btn" onclick="rtevalue("data[body]",437934);" />
The editor itself is a DIV (could be other HTML element) or IFRAME set to contentEditable / designMode = on.
If the element is a DIVyou could use it's InnerHTML property.
For the best results with an IFRAME use the below code:
procedure TForm1.Button1Click(Sender: TObject);
var
editorDoc: OleVariant;
range: OleVariant;
id: OleVariant;
begin
id := 'editor'; // frame ID
editorDoc := (WebBrowser1.Document as IHTMLDocument2).parentWindow.frames.item(id).Document;
range := editorDoc.body.createTextRange();
// range.collapse(false); // if you need to append
range.select();
range.pasteHTML('<b>Boo!</b>');
end;
Notes:
No error checking to simplify the code.
You might also try range.execCommand('inserthtml', false, MyText) (Not tested with TEmbeddedWebBrowser, but had bogus results when I tried it with plain HTML/Javascript on IE).
I have no experience concerning this TEmbeddedWebBrowser tool, but according to your post I'm thinking of a way to retrieve the form's fields. Once you know what fields it contains, I suppose you can fill them as it doesn't seem to be the purpose of your post.
Assuming there is a form declared and it is reachable: you can grab the form and
parse its .elements collection: easily if it's declared in your page
(give it an id attribute, then use a document.getElementById()),
it may still be doable if the form is declared by/inside
editor.js, using document.forms then.
Otherwise: you can get a dump
script from the Net - like this one -
and see what is printed when you call (after including editor.js
naturally) dump(data) or dump(data[body]). As data[] is
used as an argument to the rtevalue() called by your submit button's
onclick, it should contain the form's key/value pairs. The bad thing about this method is that data[] must
be filled by Javascript, so if your form has radio buttons or
checkboxes you may only see the selected ones, which is why I would give a shot at the first option before trying this trick.
About the comments, you should not directly use innerHTML to insert an HTML subtree to the document as most of the times it doesn't work (especially when forms are involved), have an appendChild() redo the work to ensure a correct document, like this:
var dummyContainer=document.createElement("span");
var dummyContainer.innerHTML="..."; //insert stuff here, because it's easy to use ;)
myContainer.innerHTML=""; //clearing your "real" container doesn't add anything to the HTML tree, it'll work - you can also use removeChild() in a loop (but it's not as easy to use!)
myContainer.appendChild(dummyContainer); //appendChild will translate properly the text inserted by innerHTML in dummyContainer into a clean HTML subtree

jQuery appended text is invisible

I'm trying to create a couple of buttons above a textarea to insert some HTML code -- a VERY poor-man's HTML editor. I have a couple of INPUT elements, and I'm using jQuery to set a click handler that will call's jQuery's append() or html() or text() functions.
The handler fires, it shows a debug alert(), but the text I'm trying to append doesn't show up in the textarea. When I inspect the textarea in Firebug, I see the text I'm appending as a child of the textarea -- but it's dimmed, as when an element's style is set to display:none. But Firebug's CSS inspector doesn't show any change to the display or visibility properties.
When I set the click handler to 'append()', and then click multiple times, in Firebug I see the text being added over and over again -- but each new chunk is still invisible. If I choose 'Edit HTML' in Firebug and then type some chars next to the appended text, the entire text block -- the text added by jQuery and the stuff I added in Firebug -- suddenly appear.
This also happens if I don't use a click handler, but call my append function using an inline handler like onclick="javascript:insert('bold');"
Anyone have any idea why the appended text is not displayed?
Here's the relevant code:
The HTML:
<input type='button' id='bold' value='B' onclick='javascript:insert("bold")' />
<textarea name='PersonalGreeting' id='PersonalGreeting'>default text</textarea>
The Javascript:
function insert( cmd ) {
switch ( cmd ) {
case 'bold':
$('#PersonalGreeting').append('<b>bold text here</b>');
break;
}
}
I would guess that jQuery is trying to append HTML DOM elements to the textarea.
Try using the val method to get and set the textarea's value, like this:
$('#PersonalGreeting').val($('#PersonalGreeting').val() + '<b>bold text here</b>');
The basic problem is that you can't put HTML inside a <textarea>. In fact, you can't append HTML elements to one at all. You could use the .val() method to change the text shown inside, but that won't make it bold. That will just make it have <b> showing as part of the text.
An off-the-shelf WYSIWYG editor like TinyMCE is free and easy to implement. Rather than reinvent the wheel (which is a lot harder than it might look), try an existing wheel out.
SLaks and VoteyDisciple are correct. You're usage of append is faulty as you are perceiving it as a string function.
From http://docs.jquery.com/Manipulation/append
Append content to the inside of every
matched element. This operation is the
best way to insert elements inside, at
the end, of all matched elements. It
is similar to doing an appendChild to
all the specified elements, adding
them into the document.
Reinventing the wheel on this one is likely more headache than its worth unless this is an attempt to create a superior, competing product or for your own experimentation.
Also, I would shy away from use of obtrusive JavaScript as you have shown in your example with onclick='javascript:insert("bold")' embedded in the input element. Instead, you'll have a more elegant solution with something like the following:
HTML
<input type="button" value="B" class="editor-command" >
<input type="button" value="I" class="editor-command" >
<input type="button" value="U" class="editor-command" >
JavaScript (not tested)
$(document).ready(function() {
var textarea = $('#PersonalGreeting')
$(".editor-command").each(function(i, node) {
textarea.val(textarea.val() + '<$>text here</$>'.replace(/\$/g, node.value);
});
});
If the main issue is the textarea not being visible, I would try this:
$('#PersonalGreeting').append('<b>bold text here</b>').show();
Might be worth a shot.
edit: In the vain of not trying to reinvent the wheel, I've had success with WYMEditor
You could do this:
$('#PersonalGreeting').append('[b]bold text here[/b]');
But that won't actually render the text as bold. To be honest I'm not actually sure how to render text as bold inside a textarea, I imainge some js trickery.

Categories