简体   繁体   English

如果将文本输入到表单输入中,如何显示div

[英]How to make a div appear if text gets typed into a form input

I have a form input which, when text gets typed into it, updates a div. 我有一个表单输入,当文本输入到它时,更新一个div。 This is what I use: 这是我使用的:

$('#CampaignTitle').keyup(function() {
    $('#titleBar').text(this.value);
}); 

That works super except I'd also like the ability to hide the div (I know how to make it start off hidden) when there's no text in the form input. 除了我还喜欢隐藏div的能力(我知道如何让它从隐藏开始)时,表格输入中没有文字。

In otherwords when someone types into the form input a div will appear and the text which is being typed into the input appears in the div. 换句话说,当某人键入表单输入时,将显示div,并且输入到输入中的文本将显示在div中。 If the user clears the input again then the div dissappears. 如果用户再次清除输入,则div消失。

Sorry I'm new to JS :) 对不起,我是JS的新手:)

Do a test to see if the text box value's length is greater than 0: 进行测试以查看文本框的值是否大于0:

$('#CampaignTitle').keyup(function() {
    if($(this).val().length > 0)
    {
        $('#titleBar').text($(this).val()).show();
    }
    else
    {
        $('#titleBar').hide();
    }
}); 

The key line here being if($(this).val().length > 0) . 这里的关键是if($(this).val().length > 0)

Something like this should work: 这样的事情应该有效:

$('#CampaignTitle').keyup(function() {

    var $titleBar = $('#titleBar');

    if(this.value.length == 0) {
       $titleBar.hide();
    }

    else { 

       if($titleBar.is(":hidden")) { 
          $titleBar.show();
       }

       $titleBar.text(this.value);
    }
}); 

It's a bit verbose and there are ways to make it a little less-verbose, but since you're still learning, I figured that this would give you a general idea of what's going on. 它有点冗长,并且有一些方法可以让它变得不那么冗长,但是既然你还在学习,我认为这可以让你大致了解发生了什么。 The is(":hidden") check can be omitted; is(":hidden")检查可以省略; that would run show() on $titleBar even if it is already visible. 这将在$titleBar上运行show() ,即使它已经可见。

Try this 尝试这个

$('#CampaignTitle').keyup(function() {
    $('#titleBar').text(this.value).show();
    if (this.value==''){ $('#titleBar').hide() }
}); 
$('#CampaignTitle').keyup(function() {
    if (this.value){
        $('#titleBar').text(this.value).show();
    }
    else {
        $('#titleBar').hide();
    }
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM