Rexluvplay Rexluvplay - 5 months ago 11
jQuery Question

How to use function parameters as class's name?

How can I use the parameters

text
and
name
to work for the class and id's name?

HTML :

<div id="text" onClick="markClickFunction("text","name");">+</div>
<div class="name">test</div>


JQUERY :

function markClickFunction(text, name) {
$('.name').slideToggle("fast");
if ($('#text').html()=="+") {
$('#text').html("-");
} else {
$('#text').html("+");
}
}

Answer

Simple string concatenation, also you need to escape " inside onlick attribute value or use '.

function markClickFunction(text, name) {
  $('.' + name).slideToggle("fast");
  var $text = $('#' + text);
  if ($text.html() == "+") {
    $text.html("-");
  } else {
    $text.html("+");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" onClick="markClickFunction('text','name');">+</div>
<div class="name">test</div>