webminal.org
webminal.org

Reputation: 47196

show button only if following div tag has some value

I have following html code - which displays a button and user clicks on it - it display some text below.

<div>
 <button class="btn-default btn-primary show-answer-button">Show</button>
 <div class="answer"></div>
 </div>

But sometimes, when user clicks the button, there is no text . (so it displays nothing). I would like to display this button only when the "answer" has some text. How to achieve this ?

I tried following (adding a id='answer-part' and insert a line at js file) but it didn't work:

 <div id="answer-part">
 <button class="btn-default btn-primary show-answer-button">Show</button>
 <div class="answer"></div>
 </div>

and add this at .js file

$('.answer-part:empty').hide();

Upvotes: 2

Views: 354

Answers (3)

Stephan Muller
Stephan Muller

Reputation: 27600

$('.answer:empty').hide().prev('button').hide();

Upvotes: 2

j08691
j08691

Reputation: 207891

Try using the length property and contents() together:

$('button.btn-default.btn-primary.show-answer-button').click(function () {
    if ($(this).next().contents().length) $(this).next().show()
})

jsFiddle example

Upvotes: 3

Amit Joki
Amit Joki

Reputation: 59232

You can do it like this:

$('.show-answer-button')[$('.answer').text() ? "show":"hide"]();

Upvotes: 2

Related Questions