super11 super11 - 5 months ago 8
CSS Question

Adding Text to Text if Condition is met

How can I in jQuery or plain Javascript add text if condition is met?

For example:

<input type="checkbox" id="foo">
<label for="foo">Foo Text</label>
<input type="checkbox" id="bar">
<label for="bar">Bar Text</label>
<p class="success" style="display: none;">Thank you for </p>
<button type="submit" id="submit-form" class="btn btn-success pull-left">SUBSCRIBE</button>


Not I need a logic that will place a "Bar Text" or "Foot Text" depending which checkbox is checked, after the submit is clicked.

I know I have to use
.is(:checked)
but I do not know how to place a text dynamically after the static "Thank you " text.

Also, I would like a jQuery and Javascript solution, if possible, for learning purposes only.

Thanks.

Answer

You can do this with map() to return array with text of label that is next of input that is checked and use join() to transform that array to text.

$('input').change(function() {
  var text = $('input').map(function() {
    if ($(this).is(':checked')) return $(this).next('label').text()
  }).get().join(', ');

  (text != '') ? $('p.success').text('Thank you for ' + text).show(): $('p.success').hide()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="foo">
<label for="foo">Foo Text</label>
<input type="checkbox" id="bar">
<label for="bar">Bar Text</label>
<p class="success" style="display: none;">Thank you for</p>
<button type="submit" id="submit-form" class="btn btn-success pull-left">SUBSCRIBE</button>

Comments