user3497277
user3497277

Reputation: 19

getting checkbox check and uncheck value

I have a checkbox below:

<%= form_for(:Communication, :html => { :id => "communication_form" }) do |f| %>
<table>
      <tr>
         <td>
            <%= f.check_box(:chkbx_Phone, { :id => "cb_Phone", :value => "false" }) %>
            <%= label_tag "Phone" %>
         </td>
      </tr>
</table>
<table width="92%">
      <tr>
         <td align="center">
            <div class="button" style="margin-left:60px;">
                <%= f.submit "Next", { :class => "buttonSearch"} %>
            </div>
         </td>          
      </tr>
</table>
<% end %>

And I want that If user check on checkbox then it get me value 1 and if user remain uncheck on checkbox then it get me value 0 after click on submit button and below is jquery code:

<script type="text/javascript">
   $("#communication_form").submit(function ( event ) {
      //alert("Hassan");
      var phone_value = $("#cb_Phone").val();
      alert(phone_value);
   });
</script>

But it show me only 1 either checkbox is checked or unchecked

Upvotes: 1

Views: 61

Answers (2)

Suraj Rawat
Suraj Rawat

Reputation: 3763

You can do this by a simple code :

$('#cb_Phone').change(function(){
      if($(this).is(':checked')){
  // do something
}
 else{ 
 // do something
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

in that case, you need to check the checked status of the element

var phone_value = $("#cb_Phone").is(':checked') ? 1 : 0;
  • .is() - returns true of at least one element in the current set matches the passed selector
  • :checked

Upvotes: 2

Related Questions