Tom Tom - 5 months ago 14
jQuery Question

Jquery not able to find checkbox ID or Name

I've got a page of checkbox that are styled.
I'm trying to return their name or ID when they are changed.

I've created a fiddle here:
https://jsfiddle.net/xpq8g13s/

That shows the issue. The jquery I'm using is :

$(document).ready(function() {
$(this).change(function() {
alert($(this).attr("name"));
alert($(this).attr("id"));
});
});


Can anyone advise why this isn't working ?

Thanks

Answer

$(this).change(function() {... is looking for the document change event, so when you refer to this later on, it is trying to get the name and id attributes of the document.

Use this event binding instead

$("#check").change(function() {
  ...

Sample

$(document).ready(function() {
  $("input[type='checkbox']").change(function() {
    alert($(this).attr("name"));
    alert($(this).attr("id"));
  });
});
.switch {
  position: relative;
  display: inline-block;
  width: 53px;
  height: 19px
}
.switch input {
  display: none
}
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s
}
.slider:before {
  position: absolute;
  content: "";
  height: 11px;
  width: 19px;
  left: 4px;
  bottom: 4px;
  background-color: #fff;
  -webkit-transition: .4s;
  transition: .4s
}
input:checked+.slider {
  background-color: #008c00
}
input:focus+.slider {
  box-shadow: 0 0 1px #2196F3
}
input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px)
}
input,
select,
textarea {
  border: 1px solid #A0A0A0;
  background: #FFF;
  padding: 3px 4px;
  color: #222;
  margin: 2px 5px 2px 0px;
}
input:focus,
select:focus,
textarea:focus {
  outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='tooltip' title='tooltip text.'>
  <img src='images/tooltip.png'>
</a>&nbsp;<b>This is my Text Label:</b>
</div>&nbsp;

<label class="switch">
  <input type="checkbox" name='check' id='check' title='checkbox' value="1">
  <div class="slider"></div>
</label>

<br/>
<input type="text" id="textinput" name="textinput" size="40" maxlength="40" autocomplete="off" placeholder="enter text here" value="" tabindex='1' disabled/>
</div>
<br/>

<label class="switch">
  <input type="checkbox" name='check2' id='check2' title='checkbox' value="1">
  <div class="slider"></div>
</label>

Comments