0

Currently Im have the following script which checks to see if a checkbox value has changed but its not working when I try to use it!

<script>
    $('input[type=checkbox]').change(function () {
        if ($(this).is(':checked')) {
            if ($(this).prev().attr('checked') && $(this).val() != $(this).prev().val()) {
                alert("previous checkbox has same value");
            }
        }
    });​
 </script>

 <input name="" type="checkbox" value="here"/>(if this was checked)
 <input name="" type="checkbox" value="here"/>(then this)
 <input name="" type="checkbox" value="there"/>(would not allow prompt alert) 
 <input name="" type="checkbox" value="here"/>(would allow)​

you can see it working here yet it does not work when i try to use it http://jsfiddle.net/rajaadil/LgxPn/7

The idea is to alert when a checked checkbox value is different from the previously checked checkbox value!

Currently my checkbox look like

<input type="checkbox" name="checkbox[]" onClick="getVal();setChecks(this)" value="`key`=<?php echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>"/>

I thought the function ('input[type=checkbox]').change(function() would get these but im wrong somewhere?

11
  • Which browser? Using .val() on a checkbox can return either "true/false" or the "here/there" you have depending on the browser. I would suggest using data- attributes for the "value" part. I would also switch from .change() to .click(); Commented Jun 27, 2012 at 20:01
  • Your script isn't in a document ready call, that's probably part of the problem Commented Jun 27, 2012 at 20:03
  • 1
    Maybe you should use .prop() instead of .attr(): stackoverflow.com/questions/5874652/prop-vs-attr Commented Jun 27, 2012 at 20:03
  • @MikeRobinson: Also no type attribute on the script. Commented Jun 27, 2012 at 20:03
  • @Cory Actually that's not required Commented Jun 27, 2012 at 20:03

4 Answers 4

1

To select the previous checked sibling checkbox, use this:

$(this).prevAll(":checked:first")

I expected to use :last, but :first is what works. This is counter-intuitive to me and inconsistent with how :first and :last usually work, but I tested it in several browsers and the result is consistent.

$(':checkbox').change(function() {
    if (this.checked) {
        var lastChecked = $(this).prevAll(":checked:first");
        if (this.value == lastChecked.val()) {
            alert("previous checked box has same value");
        }
    }
});

Demo: http://jsfiddle.net/LgxPn/15/


Edit: If by "previously checked checkbox" you mean the last box the user clicked, then you'll need to keep track of that yourself. There's no built-in jQuery method that will tell you anything about click history.

What happens when the user first checks several boxes, and then checks and immediately unchecks a box? Should the next most recently checked box be used? If so, then you need to keep track of all checked boxes, and what order they were clicked. Here's how you can keep track of the checked boxes:

var lastChecked = [];
$(':checkbox').change(function() {
    if (this.checked) {
        if (lastChecked.length && this.value == lastChecked[0].value) {
            alert("the last box you checked has the same value");
        }
        lastChecked.unshift(this);
    }
    else {
        lastChecked.splice(lastChecked.indexOf(this), 1);
    }
});​

Demo: http://jsfiddle.net/LgxPn/21/

Sign up to request clarification or add additional context in comments.

12 Comments

The problem is it only works right to left try the other direction? Im also trying to do the opposite of your code if the value does not equal if (this.value != lastChecked.val()) { alert("previous checked box has same value"); }
@tyler - please edit your question to clearly state what you mean by "the previously checked checkbox". See, your code implies you want the previous checkbox in the DOM, because you are trying to get it using .prev(). But your comment seems to imply you want to get the last checkbox the user checked. It's not clear to me what you want.
ahh know i see where i was confusing thanks so much! I do indeed mean previous selected NOT DOM! And your code seemed to work!Why does this not work when i paste it into my code? Im simply putting <html><head><script>the code here </script> </head><body><input type="checkbox" name="checkbox[]" onClick="getVal();setChecks(this)" value="key=<?php echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>"/><input type="checkbox" name="checkbox[]" onClick="getVal();setChecks(this)" value="key=<?php echo $rspatient['key']?>" class="chk" id="chk<?php echo $a++?>"/>
@tyler - this.checked = false or $(this).prop("checked", false)
please read my above im pulling my hair out over this ill be honest its my first attempt at using Jquery and i dont understand im treating it as if it where javascript wrapping it in <script tags>Also note i have it working as i want in fiddle which is only adding to the frustration
|
0

Just a guess (with some better syntax), try this:

<script type="text/javascript">
$(function() {
  $('input:checkbox').change(function() {
    if($(this).is(':checked'))
    {
       if ($(this).prev().prop('checked') && $(this).val() != $(this).prev().val()) { 
         alert("previous checkbox has same value");
       }
    }
  });​
});

</script>

5 Comments

Remember to use prop instead of attr if using JQuery 1.6+
tried this! also tired with attr and prop still no success @jaypeagi
@tyler as i mention in my solution, the issue at hand might be the != in your if statement
try this whats going on jsfiddle.net/thetylercox/gy8EQ/2
if i select the first box(there) and then another (here ) it works but if i select (here) and the (there) id doesnt alert
0

Your alert message and your if statement don't match. You check to see if the values !=, but the alert says they are equal. I'm assuming the alert is the case you want to check for. Try:

$(':checkbox').change(function() {
  var $this = $(this);
  var $prev = $this.prev();
  if($this.is(':checked')) {
    if($prev.is(':checked') && $this.val() === $prev.val()) {
      alert('Previous checkbox has same value');
    }
  }
});​

And as the others mentioned, make sure this is all within a $(document).ready() block

11 Comments

<script> $(document).ready(){ $(function(){ $('input[type=checkbox]').change(function() { if($(this).is(':checked')) { if ($(this).prev().attr('checked') && $(this).val() != $(this).prev().val()) alert("previous checkbox has same value"); } });​ }); } </script> ?
try this whats going on jsfiddle.net/thetylercox/gy8EQ/2
if i select the first box(there) and then another (here ) it works but if i select (here) and the (there) id doesnt alert
@tyler your jsfiddle demo is failing because the onclick events attached to your checkboxes isn't defined in the jsfiddle code. Try this demo: jsfiddle.net/jackwanders/gy8EQ/4 It uses my solution and appears to function as you want it to
@tyler if you select the 2nd checkbox, and then the 1st, nothing will ever happen because the function looks for .prev(), and the first checkbox has no previous sibling
|
0

This seems to work for me in Chrome:

$(function() {
    $('input[type=checkbox]').click(function() {
        if ($(this).is(':checked')) {
            if ($(this).prev().prop('checked')) {
                if ($(this).val() != $(this).prev('input[type=checkbox]').val()) {
                    alert("previous checkbox has same value");
                }
            }
        }
    });
});​

Here's a JSFiddle: http://jsfiddle.net/gy8EQ/

6 Comments

if i select the first box(there) and then another (here ) it works but if i select (here) and the (there) id doesnt alert
@tyler: So you want to look at ALL previous checkboxes? prev() only looks at the immediately adjacent sibling, not all of them. Change it to prevAll() to look at all adjacent siblings. You will have to change the code to loop over all previous checkboxes.
I want to compare the value of the last selected box to the just selected if its different alert the user
tried your fix but it didnt work! I get the warning when going from the 1st to the secont box but when trying the otherway 2nd then 1st nothing happens
@tyler: I think you're misunderstanding how prev() works, or I'm misunderstanding your intent. prev() finds the DOM element on the page immediately before the current one. Meaning: the previous element in the DOM structure, not which checkbox was most recently clicked.
|