如果显示为none,则更改按钮的文本?

时间:2016-12-09 18:47:14

标签: javascript jquery html button checkbox

我有一个正在使用数据库搜索字段的复选框列表。当有人点击复选框时,它会显示一个按钮,其中包含该复选框标签中的文本。但是,我需要该按钮在不可见时具有空文本(如果有人单击复选框以隐藏按钮)。

这是我的代码:

$(document).ready(function() {
  $('#locationAll').click(function() {
    var value = $('#locationAll').parent().text();
    $('#location-all-button').html(value + " ×").toggle('fast');
  });
});

$(document).ready(function() {
  $('.search-popup').click(function() {
    $(this).hide('fast');
  });
  if ($('.search-popup').css('display') == 'none') {
    $(this).text("");
  };
});
button {
  background-color: lightgray;
  border-radius: 20px;
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox" value="all" id="locationAll" />All
</label>
<br>
<br>
<button class="search-popup btn" id="location-all-button"></button>

出于某种原因,我无法在此处示例的复选框之前隐藏按钮,但这不是我的完整代码中的问题。如果您需要更多信息,请告诉我,我可能错过了一些内容。

1 个答案:

答案 0 :(得分:1)

好的,所以我换了一些东西。我为这个我快速制作的命名方案后面的复选框做了这个工作。该方案是按钮的ID =&#34;按钮 - &#34; + id。此外,我将所有按钮与一个类正确地隐藏在开头,以设置其默认状态。

$(document).ready(function()
{
    \\change to allow all checkboxes to trigger
    $('input[type=checkbox]').click(function()
    {
       \\change the id so it match a button when add "button-" to the start
       \\this allows me to target the matching button with any chechbox 
       $('#button-'+$(this).attr('id')).toggle('fast');
    });
    $('.search-popup').click(function()
    {
       $(this).hide('fast');
       \\ sets the check box to false so it not checked when you close it
       $("#"+$(this).text().replace(" &ensp;&times;","")).attr('checked', false);
    });

   \\hides all buttons right form the start
   $('button.search-popup').each(function()
   {
       $(this).hide();
   });
});

<label>
   <input type="checkbox" value="all" id="All" />All
</label>
<br>
<br>
<button class="search-popup btn" id="button-All">All &ensp;&times;</button>

现在,如果要在复选框已更改状态时创建和删除按钮,可以在该检查中添加if状态,以查看是否存在具有匹配id的按钮,!$(tag).size() 。

相关问题