Javascript在评论表单上显示/隐藏名称字段?

时间:2015-06-04 01:34:58

标签: javascript jquery

默认情况下如何隐藏nickname字段,然后在用户点击textarea时显示该字段?

<div class="input-box">
<textarea name="detail" placeholder="Input here" id="review_field" cols="5" rows="3" class="required-entry"></textarea>
</div>

<div class="col-sm-8" >
<input type="text" name="nickname" placeholder="input name!" id="nickname_field" class="input-text required-entry"  />
</div>

4 个答案:

答案 0 :(得分:1)

选择昵称字段,在昵称上设置display: none,为textarea指定一个点击处理程序,删除显示设置,将其恢复为自然状态。

var nickname = document.getElementById('nickname_field');
nickname.style.display = 'none';
document.getElementById("review_field").onclick = function() {
    nickname.style.display = '';
};
<div class="input-box">
<textarea name="detail" placeholder="Input here" id="review_field" cols="5" rows="3" class="required-entry"></textarea>
</div>

<div class="col-sm-8" >
<input type="text" name="nickname" placeholder="input name!" id="nickname_field" class="input-text required-entry"  />
</div>

答案 1 :(得分:0)

请尝试以下代码:

  $(function(){
    // hide nickname field on initial dom ready state
    $('#nickname_field').hide();  
    // add click event onto review_field    
    $('#review_field').click(function(){
      //show nickname field when textarea was clicked
      $('#nickname_field').show();
    });
 });

<强> DEMO

答案 2 :(得分:0)

使用css最初隐藏元素。如果您使用JS来隐藏它,那么在加载页面时可能会有一些时间可以看到该元素。

$('#review_field').on('click', function() {
  $('#nickname_field').show();
});
#nickname_field {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-box">
<textarea name="detail" placeholder="Input here" id="review_field" cols="5" rows="3" class="required-entry"></textarea>
</div>

<div class="col-sm-8" >
<input type="text" name="nickname" placeholder="input name!" id="nickname_field" class="input-text required-entry"  />
</div>

答案 3 :(得分:-1)

这是一个可能的解决方案:

&#13;
&#13;
var nickName = $('#nickname_field');
var reviewField = $('#review_field');

nickName.hide();

reviewField.on('keypress keydown keyup', function(){
  
 nickName.show();
  
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-box">
<textarea name="detail" placeholder="Input here" id="review_field" cols="5" rows="3" class="required-entry"></textarea>
</div>

<div class="col-sm-8" >
<input type="text" name="nickname" placeholder="input name!" id="nickname_field" class="input-text required-entry"  />
</div>
&#13;
&#13;
&#13;