tomalvi tomalvi - 8 months ago 19
Javascript Question

Hiding/showing paragraphs according to checkbox's checked status and input text value

There are 4 paragraphs, a blank text field, 1 checkbox and a button.

I want 1 paragraph to hide when I check the checkbox and write "1" in the field, 2 paragraphs to hide when I check the checkbox and write down 2, etc.


<p class="p1">P1</p>
<p class="p2">P2</p>
<p class="p3">P3</p>
<p class="p4">P4</p>

<input id="txt" type="text" name="fld" value="" /> <br /> <br />

P <input id="pcheck" type="checkbox" name="pcheckbox" /> <br /> <br />

<input id="disapp" type="button" value="Disappear" />

The JavaScript :

$("#disapp").click(function() {
if(($("#pcheck").is(":checked")) && ($(#txt).val()=="1") {

I tried formatting it also like this:

$(disapp).click(function() {
if(($pcheck.checked) && ($txt.value()=="1")) {

And I don't know which formatting is more correct and I don't know how to make it work.


Your code has some syntax problems, which causes errors. You can use the developer console in your browser to see the errors.

What's wrong with your first script block:

$(#txt).val() doesn't work because a selector needs to be a string. Change it to $('#txt').val().

Also your if statement misses a closing parentheses. It should be if(($("#pcheck").is(":checked")) && ($(#txt).val()=="1"))

Working example:

Your second script block makes the same selector error multiple times, as long as you don't define the variables disapp, $pcheck etc. it will throw errors.