如果输入中的文本不为空,则更改宽度

时间:2017-05-20 00:55:21

标签: javascript jquery input width

如果输入字段中存在一些文本,我想将输入字段的宽度设为100%。 我尝试了下面的jquery命令,但没有运气。

$("#field").change(function(){
      if($(this).val() != '')
      {
         $(this).css("width",100%);
      }
  });

$('#field').on('change', function() { 
     if($(this).val()!='')
     {
             $(this).css("width",100%);
     }
    });

任何人都可以告诉我我做错了什么或建议任何替代方法吗?

4 个答案:

答案 0 :(得分:3)

你知道元素丢失焦点后会发生“更改”事件,对吧?如果您想立即更改,请使用input事件。

此外,100%需要在引号中,因为这是您希望使用的实际值。

// the change event triggers after the focus is lost on the element
$('#field').on('change', function() { 
     if($(this).val()!=='')     {
             $(this).css("width","100%");
     }
});

// The input event fires as the value changes
$('#field2').on('input', function() { 
     if($(this).val()!=='')     {
             $(this).css("width","100%");
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
<input id="field" placeholder="type and then hit TAB">
</div>

<div>
<input id="field2" placeholder="just type">
</div>

答案 1 :(得分:1)

您需要将字符串设置为width属性的值

像:

$(this).css("width","100%");

否则js会将%解释为模数运算符而不是单位

答案 2 :(得分:1)

因为100%不是数字。这是字符串;

&#13;
&#13;
$entityarray['nodes'][] = array( 'id'    => 'example@email.com'
                               , 'group' => 1
                               );
&#13;
$('#field').on('input', function() {
     if($(this).val() != '')
     {
             $(this).css("width","100%");
     }else{
       $(this).css("width","20%");
     }
});
&#13;
&#13;
&#13;

答案 3 :(得分:1)

是的,您有拼写错误,将100%更改为"100%"。如果您想立即更改,请使用on keypress或更好on input

&#13;
&#13;
$('#field').on('input', function() {
  if ($(this).val() != '') {
    $(this).css("width", "100%");
  }else{
    $(this).css("width", "50%");
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field" style="width:50%;" />
&#13;
&#13;
&#13;

相关问题