qanknku
qanknku

Reputation: 147

javascript toggling to show and hide specific tag

As written below, I have form that sends some information. The Toggle button below exists to show specific <td>tag and hide the others when clicked. I marked with here which should be shown when toggled, and here2 which should be hidden when toggled.

                    <td> <button id="to">Toggle</button> </td>
   here2 --->       <td> <img src="https: ~ "</td>
                    <td> </td>
                <% end %>
                <%= mv.hidden_field :tid, :value => movie.id %>
                <%= mv.hidden_field :nid, :value => (@matchables[movie.title] != 0 ? @matchables[movie.title].naver_id : "") %>
  here -->      <td><%= mv.text_field :nid, class: 'input-mini', placeholder: 'ID', value: (@matchables[movie.title] != 0 ? @matchables[movie.title].movie_id : "") %></td>
                <td></td>
                <td></td>
                <td><%= link_to 'delete', delete_item_admin_theaters_path(theater_id: movie.id), class: "btn btn-primary" %></td>
              </tr>
          <% end %>
      <% end %>
      </tbody>
    </table>
    <%= submit_tag('Register' , class: "btn btn-primary btn-lg") %>
    <% end %>
  </div>
</div>

To do this I wrote simple scripts like below.

<script type="text/javascript">
        $("button").click(function () { $("td").toggle(); });
</script>

However, I got some problems.

The first one is that when I click the button, it actually seems like to activate submit_tag as well. There by rendering weird page as well.

Second problem is that when I click the button, since td tag is not specified, it erases all the td tags.

Also I'd like to know how can set visibility of tags separately so that toggling can effectively work.

Upvotes: 1

Views: 67

Answers (1)

Teodor Marinescu
Teodor Marinescu

Reputation: 186

For the second problem: I would give the tds some unique ids. And then run toggle only on those ids using jquery id-selectors You also need to make sure the "here td" is hidden when the page is loaded. You can do this by adding a css option for hiding it (like display:none), or hiding it at document load using jquery $("#theId").hide().

Now assuming the "here td's" ID is "movie_title" and the "here2 td's" ID is "image" your script should be something like:

<script type="text/javascript">
        $("button").click(function () { $("#movie_title").toggle(); $("#image").toggle();  });
</script>

For the first problem: Using the $("button") selector will select all your buttons which could potentially cause problems. Try suing unique ids like you already have on your button (id="to") and then use id-selectors like $("#to")

Good luck!

/Teo

Upvotes: 1

Related Questions