Anson Aştepta
Anson Aştepta

Reputation: 1143

check if element has something

First, I receive a row of data from JSON and print the data on the HTML like

<p id="checker">1+2</p> 

and below i have some checkboxes

<p style="display:none" id="1">cat</p>
<p style="display:none" id="2">dog</p>
<p style="display:none" id="3">fish</p>

And I'd like to make some p tags appear if the if statement is true

if ($("#checker").html() == "1") {
  $("#1").css("display", "block");
}

elseif($("#checker").html() == "2") {
  $("#2").css("display", "block");
}

but I realized that this can't satisfy my need. Is there another solution for this task?

Upvotes: 3

Views: 126

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115262

Split the string and iterate over them, based on the value get element and show.

$('#checker')
  .html() // get html content
  .split('+') // split string by +
  .forEach(function(v) { // iterate over them
    $('#' + $.trim(v)).show() // get element by id and show
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="checker">1+2</p>
<p style="display:none" id="1">cat</p>
<p style="display:none" id="2">dog</p>
<p style="display:none" id="3">fish</p>

Upvotes: 3

Hongbin Wang
Hongbin Wang

Reputation: 1186

Have something does not mean ==. You can use indexOf to check if a string has something or not.

Try this

if($("#checker").html().indexOf("1")!=-1){
        $("#1").css("display","block");
     }

Upvotes: 0

Michael Gaskill
Michael Gaskill

Reputation: 8042

Yes, you can use the jQuery show() function, like so:

if($("#checker").html()=="1"){
    $("#1").show();
}
elseif($("#checker").html()=="2"){
    $("#2").show();
}

If you need to hide them again, you can use the hide() function the same way.

Upvotes: 0

Related Questions