text_input: Placeholder keeps RTL while only change input to be LTR - html

The text-input now is RTL(both placeholder and the input). The attributes were set at some where else.
My question is how can I make a change that only changes the input to be LTR, while the placeholder remains RTL.
Example:
Initially, the text box is like
When it gets focus, the input should be LTR. Because the URL is LTR.
If user didn't type anything and the box lost focus, the placeholder should show up and keep RTL.
Can anyone help me with this? Thanks.

You can use this code.
//jQuery
(function($) {
$.fn.dir_auto = function() {
var selector = '.inputs-nyn[dir="auto"]';
var sclass = "auto-nyn05";
var ftime = true;
if ( $(selector).length ) {
$(document).on("keyup", selector , function() {
if( ftime || !$(this).val() ){
if( !$(this).val() ){
$(this).addClass(sclass);
ftime = true;
}
else{
$(this).removeClass(sclass);
ftime = false;
}
}
});
}
};
})(jQuery);
$(document).ready(function() {
$.fn.dir_auto();
});
//css
body{
direction: rtl;
}
.inputs-nyn.auto-nyn05[dir="auto"] {
direction: rtl;
}
.inputs-nyn[dir="auto"]::placeholder {
text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- HTML -->
<input class="inputs-nyn auto-nyn05" dir="auto" placeholder="متن فارسی..." type="text">

You cannot do that with HTML markup, since the dir attribute sets the basic directionality of all attributes of the element (and the element content, if it has content).
What you can do is to override the basic directionality for an attribute at the character level. This means that you set the element’s directionality to LTR (so that the value will appear that way) but use U+202B RIGHT-TO-LEFT EMBEDDING at the start of the placeholder value and U+202C POP DIRECTIONAL FORMATTING at its end. This will make it an “RTL island”. E.g.,
<input ... dir=ltr placeholder="‫...‬">
Unfortunately, the placeholder text will then appear as left-aligned (due to the element’s directionality). But the directionality of that text will be RTL.

Related

Check if text is being entered in input using Javascript/jQuery

I am trying to hide a placeholder while the input is being used and while there's text inside the input. Here's a simplified version of the HTML for the input and placeholder:
<div id="search-placeholder"><span class="fa fa-search"></span> Search</div>
<input id="search-input" type="text" name="search" />
I tried using jQuery but it does not return the desired result:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
$('#search-placeholder').fadeIn(100);
});
});
The placeholder will hide when the input is selected, as it should. But it will show again when the user clicks elsewhere, even while the input is not empty! The placeholder is visible on top of the input value, so I tried a different approach:
$('#search-input').change(function(){
if($('#search-input').val() = '') {
$('#search-placeholder').fadeIn(100);
}else{
$('#search-placeholder').fadeOut(100);
}
})
Unfortunately, this only works when the user clicks elsewhere. The placeholder still shows while typing and while the input is selected, again showing itself on top of the input value. How do I hide <div id="search-placeholder"> while <div id="search-input"> is not empty, or when the input is selected by clicking or tapping it (on focus)?
Maybe try to check the value of the input in the focusout event and only show the placeholder if it's empty:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
if($('#search-input').val() === '')
{
$('#search-placeholder').fadeIn(100);
}
});
});
I think you could extract the $('#search-input') and $('#search-placeholder') elements to variables, so the code becomes a bit more readable.
You do this using javascript and jquery
jquery :-
$(document).ready(function(){
$('#search-input').focus(function() {
$('#search-placeholder').fadeOut(100);
});
$('#search-input').focusout(function() {
if($('#search-input').val() === '') {
$('#search-placeholder').fadeIn(100);
}
});
});
javascript
var searchInput = document.getElementById("search-input");
var searchPlaceholder = document.getElementById("search-placeholder");
searchInput.onfocus = function() {
searchPlaceholder.style.display = "none";
}
searchInput.onfocusout = function() {
if(this.value == "") {
searchPlaceholder.style.display = "block";
}
}
if you want to add fade-in fade-out transitions in javascript method use css transition property- transition: opacity 1s and instead of changing style.display change style.opacity to 1(show) and 0(hide)

How to create a "placeholder" for DIV that act like textfield?

Div don't have a placeholder attribute
<div id="editable" contentEditable="true"></div>
I want <Please your enter your Name> to show in DIV when the User backspace the whole text in the DIV, or no text on inside, How can I do it?
Here is a pure CSS only solution:-
<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-ph)
}
</style>
Here, we basically select all contentEditable <divs> that are empty & blurred. We then create a pseudo element before the CSS selection (the editable div) and fix our placeholder text (specified the data-ph attribute) as its content.
If you are targeting old school CSS2 browsers, change all occurrences of data-ph to title
Correction.......the :empty selector is not supported in IE version 8 and earlier.
What I find in other answers is that when using :not(:focus) pseudo class, I have to click again in order to get the blinking cursor and be able to type. Such issue doesn't happen if I click on an area other than the placeholder.
My workaround is simply removing :not(:focus). Even though in this way the placeholder will still be there after I click on the editable div, I'm able to type no matter where in the div I click, and the placeholder disappears immediately after I type something.
BTW, I inspected YouTube's comment div implementation, seems they are doing the same thing, e.g. #contenteditable-root.yt-formatted-string[aria-label].yt-formatted-string:empty:before
.editableDiv1,
.editableDiv2 {
border-bottom: 1px solid gray;
outline: none;
margin-top: 20px;
}
.editableDiv1[contentEditable="true"]:empty:not(:focus):before {
content: attr(placeholder)
}
.editableDiv2[contentEditable="true"]:empty:before {
content: attr(placeholder)
}
<div class="editableDiv1" contentEditable=true placeholder="If you click on this placeholder, you have to click again in order to get the blinking cursor and type..."></div>
<div class="editableDiv2" contentEditable=true placeholder="Click on placeholder is fine, it'll disappear after you type something..."></div>
You can try this one !
html:
<div contentEditable=true data-text="Enter name here"></div>
css:
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-text) }
check it out (demo)
in HTML
<div id="editable" contenteditable="true">
<p>Please your enter your Name</p>
</div>
in JavaScript
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$("#editable").click(function() {
$("#editable").selectText();
});
jsFiddle

Having a permanent value in an input field while still being able to add text to it

I don't know if this is possible but I would like to have an input field where I would have a value that is not editable by the user.
However, I don't want the input field to be "readonly" because I still want the user to be able to add text after the value.
If you have any idea on how to do this, let me know please that would help me a lot.
EDIT: I use html forms.
You can position the text on top of the input field to make it look as if it is inside it. Something like this:
<input type="text" name="year" style="width:3.5em;padding-left:1.5em;font:inherit"><span style="margin-left:-3em;margin-right:10em;">19</span>
This way your input field will start with "19" which can not be edited, and the user can add information behind this.
Basically what you do is set the input field to a fixed width, so that you know how much negative margin-left to give the span with your text in it in order for it to be positioned exactly at the start of the input field.
You might need to fiddle with the margin-left of the span depending on the rest of your css.
Then also adding pedding-left to the input field, to make sure the user starts typing after your text and not under it.
font:inherit should make sure both your text and the text typed by the user are in the same font.
And if you want to put anything to the right of this input field, do add margin-right to the span with your text, as otherwise other content might start running over your input field as well.
seems a little weird to me ..why not just use a text output and afterwards the input field?
like sometimes used for the birthdate (although, maybe not anymore..)
birthyear: 19[input field]
edit:
with some javascript stuff you could realise something like that you asked for, though
an input field with text and catching keystrokes within that field while only allowing some after what you want to be always there - but, well, you would need to use js ..and if its just for that, Id rather say its not necessary
edit:
if you want to use a trick just for the viewer you could use a background-image/border-style that surrounds a text and the input field, thus making it look like text and input are the same input-box.
Sounds like you want placeholder text. In HTML5 you can set the placeholder attribute on any input element. This will work in modern browsers.
<input type="email" placeholder="jappleseed#appletree.com" name="reg_email" />
Now, for older browsers this won't work. You'll need a JavaScript alternative to provide the same UI value.
This can work for all browsers:
<input type="text" value="Search" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}">
but it's not recommended because there is a better way (really, it's a combination of the first two approaches): Use HTML5 markup for new browsers; jQuery and modernizr for old browsers. This way you can have only one set of code that will support all user cases.
Taken directly from webdesignerwall.com:
<script src="jquery.js"></script>
<script src="modernizr.js"></script>
<script>
$(document).ready(function(){
if(!Modernizr.input.placeholder){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
</script>
[You'll need both jquery.js and modernizr.js installed in the same folder as your webpage.]
Note: I have a feeling that a little more research might reveal that modernizr isn't needed for this at all, though I could be wrong about that particular point.
Perhaps, then, you want a select menu?
<select name="mySelectMenu">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Sorry if this isn't what you want either. I'm grasping at straws because what you are asking for is very vague. Maybe you should give an example of what one of these 'editable but not editable' inputs would be used for.
Also, you could use a select and a text input.
The main problem is to determine the position of the cursor. This can be done e.g. using the following function:
function getCaret(el) {
var pos = -1;
if (el.selectionStart) {
pos = el.selectionStart;
}
else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r != null) {
var re = el.createTextRange();
var rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
return pos;
}
Now you can install an event handler for the key press and check whether the pressed key was inside the immutable part of the value of the textarea. If it was there the event handler returns false, otherwise true. This behavior can be wrapped into a simple object:
function Input(id, immutableText) {
this.el = document.getElementById(id);
this.el.value = immutableText;
this.immutableText = immutableText;
this.el.onkeypress = keyPress(this);
}
function keyPress(el) {
return function() {
var self = el;
return getCaret(self.el) >= self.immutableText.length;
}
}
Input.prototype.getUserText = function() {
return this.el.value.substring(this.immutableText.length);
};
var input = new Input("ta", "Enter your name: ");
var userText = input.getUserText();
You can check it on jsFiddle (use Firefox or Chrome).
I came up with this:
```
if (e.target.value == '' || e.target.value.length <= 3) {
e.target.value = '+91-';
}
```

highlight word in div using javascript

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else
You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.
I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...
Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.
To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.

Select dropdown with fixed width cutting off content in IE

The issue:
Some of the items in the select require more than the specified width of 145px in order to display fully.
Firefox behavior: clicking on the select reveals the dropdown elements list adjusted to the width of the longest element.
IE6 & IE7 behavior: clicking on the select reveals the dropdown elements list restricted to 145px width making it impossible to read the longer elements.
The current UI requires us to fit this dropdown in 145px and have it host items with longer descriptions.
Any advise on resolving the issue with IE?
The top element should remain 145px wide even when the list is expanded.
Thank you!
The css:
select.center_pull {
background:#eeeeee none repeat scroll 0 0;
border:1px solid #7E7E7E;
color:#333333;
font-size:12px;
margin-bottom:4px;
margin-right:4px;
margin-top:4px;
width:145px;
}
Here's the select input code (there's no definition for the backend_dropbox style at this time)
<select id="select_1" class="center_pull backend_dropbox" name="select_1">
<option value="-1" selected="selected">Browse options</option>
<option value="-1">------------------------------------</option>
<option value="224">Option 1</option>
<option value="234">Longer title for option 2</option>
<option value="242">Very long and extensively descriptive title for option 3</option>
</select>
Full html page in case you want to quickly test in a browser:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>dropdown test</title>
<style type="text/css">
<!--
select.center_pull {
background:#eeeeee none repeat scroll 0 0;
border:1px solid #7E7E7E;
color:#333333;
font-size:12px;
margin-bottom:4px;
margin-right:4px;
margin-top:4px;
width:145px;
}
-->
</style>
</head>
<body>
<p>Select width test</p>
<form id="form1" name="form1" method="post" action="">
<select id="select_1" class="center_pull backend_dropbox" name="select_1">
<option value="-1" selected="selected">Browse options</option>
<option value="-1">------------------------------------</option>
<option value="224">Option 1</option>
<option value="234">Longer title for option 2</option>
<option value="242">Very long and extensively descriptive title for option 3</option>
</select>
</form>
</body>
</html>
For IE 8 there is a simple pure css-based solution:
select:focus {
width: auto;
position: relative;
}
(You need to set the position property, if the selectbox is child of a container with fixed width.)
Unfortunately IE 7 and less do not support the :focus selector.
I did Google about this issue but didn't find any best solution ,So Created a solution that works fine in all browsers.
just call badFixSelectBoxDataWidthIE() function on page load.
function badFixSelectBoxDataWidthIE(){
if ($.browser.msie){
$('select').each(function(){
if($(this).attr('multiple')== false){
$(this)
.mousedown(function(){
if($(this).css("width") != "auto") {
var width = $(this).width();
$(this).data("origWidth", $(this).css("width"))
.css("width", "auto");
/* if the width is now less than before then undo */
if($(this).width() < width) {
$(this).unbind('mousedown');
$(this).css("width", $(this).data("origWidth"));
}
}
})
/* Handle blur if the user does not change the value */
.blur(function(){
$(this).css("width", $(this).data("origWidth"));
})
/* Handle change of the user does change the value */
.change(function(){
$(this).css("width", $(this).data("origWidth"));
});
}
});
}
}
Here is a little script that should help you out:
http://www.icant.co.uk/forreview/tamingselect/
For a simple Javascript-free solution, adding a title-attribute to your <option>s holding the text might be enough, depending on your requirements.
<option value="242" title="Very long and extensively descriptive text">
Very long and extensively descriptive text
</option>
This will show the cut-off text in a tool-tip fashion on hovering the <option>, regardless of the width of the <select>.
Works for IE7+.
Not javascript free i'm afraid, but I managed to make it quite small using jQuery
$('#del_select').mouseenter(function () {
$(this).css("width","auto");
});
$('#del_select').mouseout(function () {
$(this).css("width","170px");
});
Simply you can use this plugin for jquery ;)
http://plugins.jquery.com/project/skinner
$(function(){
$('.select1').skinner({'width':'200px'});
});
Small, but hopefully useful update to the code from MainMa & user558204 (thanks guys), which removes the unnecessary each loop, stores a copy of $(this) in a variable in each event handler as it's used more than once, also combined the blur & change events as they had the same action.
Yes, it's still not perfect as it resizes the select element, rather than just the drop-down options. But hey, it got me out of a pickle, I (very, very unfortunately) still have to support an IE6-dominant user base across the business.
// IE test from from: https://gist.github.com/527683
var ie = (function () {
var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
} ());
function badFixSelectBoxDataWidthIE() {
if (ie < 9) {
$('select').not('[multiple]')
.mousedown(function() {
var t = $(this);
if (t.css("width") != "auto") {
var width = t.width();
t.data("ow", t.css("width")).css("width", "auto");
// If the width is now less than before then undo
if (t.width() < width) {
t.unbind('mousedown');
t.css("width", t.data("ow"));
}
}
})
//blur or change if the user does change the value
.bind('blur change', function() {
var t = $(this);
t.css("width", t.data("ow"));
});
}
}
A different approach:
instead of a select make it an edit box, disabled so noone can enter anything manually or change contents after selection
another hidden edit to contain an id of a selected option (explained below)
make a button [..] and script it to show that div below
make a hidden div with absolute position under or near the edit box
make that div to contain a select with style size="6" (to show 6 options and a scrollbar rather than a drop-down list) and a button "select" and maybe "cancel"
Do not style width so the whole thing will assume width of the widest option or the button plus maybe some padding of your choice
script the "select" button to copy id of the selected option to the hidden edit box and it's value to the visible one, also to hide the div again.
4 simple javascript commands total.
I found a pretty straightforward fix for this. In the <select> html element add these properties:
onmouseover="autoWidth(this)"
onblur="resetWidth(this)"
So whenever user clicks on that the width will automatically expand, and user moves out of the select box, the width will be reset to original.
similar solution can be found here using jquery to set the auto width when focus (or mouseenter) and set the orignal width back when blur (or mouseleave) http://css-tricks.com/select-cuts-off-options-in-ie-fix/.
for (i=1;i<=5;i++){
idname = "Usert" + i;
document.getElementById(idname).style.width = "100%";
}
I used this way to showed the drop down list when the width is not showed correctly.
It work for IE6, Firefox and Chrome.
A full fledged jQuery plugin is available, check out the demo page: http://powerkiki.github.com/ie_expand_select_width/
disclaimer: I coded that thing, patches welcome
Why would anyone want a mouse over event on a drop down list? Here's a way of manipulating IE8 for the way a drop down list should work:
First, let's make sure we are only passing our function in IE8:
var isIE8 = $.browser.version.substring(0, 2) === "8.";
if (isIE8) {
//fix me code
}
Then, to allow the select to expand outside of the content area, let's wrap our drop down lists in div's with the correct structure, if not already, and then call the helper function:
var isIE8 = $.browser.version.substring(0, 2) === "8.";
if (isIE8) {
$('select').wrap('<div class="wrapper" style="position:relative; display: inline-block; float: left;"></div>').css('position', 'absolute');
//helper function for fix
ddlFix();
}
Now onto the events. Since IE8 throws an event after focusing in for whatever reason, IE will close the widget after rendering when trying to expand. The work around will be to bind to 'focusin' and 'focusout' a class that will auto expand based on the longest option text. Then, to ensure a constant min-width that doesn't shrink past the default value, we can obtain the current select list width, and set it to the drop down list min-width property on the 'onchange' binding:
function ddlFix() {
var minWidth;
$('select')
.each(function () {
minWidth = $(this).width();
$(this).css('min-width', minWidth);
})
.bind('focusin', function () {
$(this).addClass('expand');
})
.change(function () {
$(this).css('width', minWidth);
})
.bind('focusout', function () {
$(this).removeClass('expand');
});
}
Lastly, make sure to add this class in the style sheet:
select:focus, select.expand {
width: auto;
}
Not javascript free, I am afraid too and my solution do require a js library, however, you can only use those files which you need rather than using them all, maybe best suited for those who are already using YUI for their projects or deciding which one to use. Have a look at: http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/
My blog post also discusses other solutions as well, one is referenced back to here on stackoverflow, why I went back to create my own SELECT element is because of simple reason, I don't like mouseover expand events. Maybe if that helps anyone else too!
The jquery BalusC's solution improved by me. Used also: Brad Robertson's comment here.
Just put this in a .js, use the wide class for your desired combos and don't forge to give it an Id. Call the function in the onload (or documentReady or whatever).
As simple ass that :)
It will use the width that you defined for the combo as minimun length.
function fixIeCombos() {
if ($.browser.msie && $.browser.version < 9) {
var style = $('<style>select.expand { width: auto; }</style>');
$('html > head').append(style);
var defaultWidth = "200";
// get predefined combo's widths.
var widths = new Array();
$('select.wide').each(function() {
var width = $(this).width();
if (!width) {
width = defaultWidth;
}
widths[$(this).attr('id')] = width;
});
$('select.wide')
.bind('focus mouseover', function() {
// We're going to do the expansion only if the resultant size is bigger
// than the original size of the combo.
// In order to find out the resultant size, we first clon the combo as
// a hidden element, add to the dom, and then test the width.
var originalWidth = widths[$(this).attr('id')];
var $selectClone = $(this).clone();
$selectClone.addClass('expand').hide();
$(this).after( $selectClone );
var expandedWidth = $selectClone.width()
$selectClone.remove();
if (expandedWidth > originalWidth) {
$(this).addClass('expand').removeClass('clicked');
}
})
.bind('click', function() {
$(this).toggleClass('clicked');
})
.bind('mouseout', function() {
if (!$(this).hasClass('clicked')) {
$(this).removeClass('expand');
}
})
.bind('blur', function() {
$(this).removeClass('expand clicked');
})
}
}
Its tested in all version of IE, Chrome, FF & Safari
// JavaScript code
<script type="text/javascript">
<!-- begin hiding
function expandSELECT(sel) {
sel.style.width = '';
}
function contractSELECT(sel) {
sel.style.width = '100px';
}
// end hiding -->
</script>
// Html code
<select name="sideeffect" id="sideeffect" style="width:100px;" onfocus="expandSELECT(this);" onblur="contractSELECT(this);" >
<option value="0" selected="selected" readonly="readonly">Select</option>
<option value="1" >Apple</option>
<option value="2" >Orange + Banana + Grapes</option>
I've got yet another contribution to this. I wrote this a while back that you may find helpful: http://dpatrickcaldwell.blogspot.com/2011/06/giantdropdown-jquery-plugin-for-styling.html
It's a jquery plugin to make a styleable unordered list backed by the hidden select element.
The source is on github: https://github.com/tncbbthositg/GiantDropdown
You'd be able to handle behaviors and styles on the UL that you can't with the SELECT. Everything else should be the same because the select list is still there, it's just hidden but the UL will use it as a backing data store (if you will).
I wanted this to work with selects that I added dynamically to the page, so after a lot of experimentation, I ended up giving all the selects that I wanted to do this with the class "fixedwidth", and then added the following CSS:
table#System_table select.fixedwidth { width: 10em; }
table#System_table select.fixedwidth.clicked { width: auto; }
and this code
<!--[if lt IE 9]>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(document).on(
{
'mouseenter': function(event) {
jQuery(this).addClass('clicked');
},
'focusout change blur': function() {
jQuery(this).removeClass('clicked');
}
}, 'select.fixedwidth');
});
</script>
<![endif]-->
A couple of things to note:
In spite of the fact that my selects are all in a table, I had to do "on" to the jQuery(document).on instead of to jQuery('table#System_table').on
In spite of the fact that the jQuery documentation says to use "mouseleave" instead of "blur", I found that in IE7 when I moved the mouse down the drop down list, it would get a mouseleave event but not a blur.
Here is a solution that actually works.
It sets the width in IE and doesn't mess up your page layout and doesn't close the dropdown when you mouse over the select options like some of the other solutions on this page.
You will need however to change the margin-right value and width values to match what you have for your select fields.
Also you can replace the $('select') with $('#Your_Select_ID_HERE') to only effect a specific select field. As well you will need to call the function fixIESelect() on the body onload or via jQuery using DOM ready as I did in my code below:
//////////////////////////
// FIX IE SELECT INPUT //
/////////////////////////
window.fixIESelect_clickset = false;
function fixIESelect()
{
if ($.browser.msie)
{
$('select').mouseenter(function ()
{
$(this).css("width","auto");
$(this).css("margin-right","-100");
});
$('select').bind('click focus',function ()
{
window.fixIESelect_clickset = true;
});
$('select').mouseout(function ()
{
if(window.fixIESelect_clickset != true)
{
$(this).css("width","93px");
window.fixIESelect_clickset = false;
}
});
$('select').bind('blur change',function ()
{
$(this).css("width","93px");
});
}
}
/////////////
// ONLOAD //
////////////
$(document).ready(function()
{
fixIESelect();
});
For my layout, I didn't want a hack (no width increasing, no on click with auto and then coming to original). It broke my existing layout. I just wanted it to work normally like other browsers.
I found this to be exactly like that :-
http://www.jquerybyexample.net/2012/05/fix-for-ie-select-dropdown-with-fixed.html
A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):
<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
<select onchange='jump();'>
<!-- '▼(▼)' produces a fake dropdown indicator -->
<option value=''>Jump to ... ▼</option>
<option value='1'>http://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie</option>
...
</select>
</div>
A pure css solution : http://bavotasan.com/2011/style-select-box-using-only-css/
.styled-select select {
background: transparent;
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 0;
height: 34px;
-webkit-appearance: none;
}
.styled-select {
width: 240px;
height: 34px;
overflow: hidden;
background: url(http://cdn.bavotasan.com/wp-content/uploads/2011/05/down_arrow_select.jpg) no-repeat right #ddd;
border: 1px solid #ccc;
}
<div class="styled-select">
<select>
<option>Here is the first option</option>
<option>The second option</option>
</select>
</div>
Best solution: css + javascript
http://css-tricks.com/select-cuts-off-options-in-ie-fix/
var el;
$("select")
.each(function() {
el = $(this);
el.data("origWidth", el.outerWidth()) // IE 8 can haz padding
})
.mouseenter(function(){
$(this).css("width", "auto");
})
.bind("blur change", function(){
el = $(this);
el.css("width", el.data("origWidth"));
});