javascriptinternet-explorer-10

Dynamic alignment for textbox in IE10 is not working


I am trying to change the alignment of textbox dynamically and it is not working. But if I give through on load of widget that is working fine.

code; HTML

 <input type="text" id="text1" style="text-align:center;width:80px" value="abc">
 <input type='button' id="btn" value="click">

JavaScript:

 document.getElementById('btn').onclick = function(){
    console.log(document.getElementById('text1').style.textAlign);
    document.getElementById('text1').style['text-align'] = "left";   
 }

Solution

  • You can fix this bug by using the ::-ms-value pseudo element. You need to add some padding so it triggers a repaint. As it is the pseudo element rather than the actual element you are adding padding too, it looks like it doesn't change the actual width of the input. It also has the advantage of not being applied to non-IE browsers.

    CSS:

    .update::-ms-value {
        padding-right: 1px;    
    }
    

    JS:

    document.getElementById('text1').className += "update";
    

    http://jsfiddle.net/yHnLK/22/

    Of course, you’d want to store the text1 element in a variable so you don't keep calling getElementById each time. Adding the text-align: left; via CSS would also be better, rather than adjusting the style object directly.