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?

gilly3
  • 87,962
  • 25
  • 144
  • 176

4 Answers4

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/

gilly3
  • 87,962
  • 25
  • 144
  • 176
  • 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"); } –  Jun 27 '12 at 22:24
  • @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. – gilly3 Jun 27 '12 at 22:47
  • 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 –  Jun 27 '12 at 23:37
  • @tyler - `this.checked = false` or `$(this).prop("checked", false)` – gilly3 Jun 27 '12 at 23:41
  • 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 –  Jun 27 '12 at 23:43
  • You have to include jQuery. jQuery is a JavaScript library. Your page can only use that library if you include it on your page. Above your `` – gilly3 Jun 27 '12 at 23:48
  • http://jsfiddle.net/thetylercox/LgxPn/24/ I posted into the html section so you can get an idea of what i have –  Jun 27 '12 at 23:49
  • I tried this still no luck a link to where http://soldbybillcox.com/treasure/test3.html im using chrome should this matter –  Jun 27 '12 at 23:51
  • Also, wrap your code in a document ready handler. Ie, `$(function(){ /* your code here */ });`. See here: http://jsfiddle.net/LgxPn/26/ – gilly3 Jun 27 '12 at 23:57
  • ok this is working but if i get the alert once for a value it wont happen again aka click 1 then 2 get alert (I put the code into uncheck the box So its unchecked) Now if i click 2 again no alert! Im sure its registering the last clicked as 2 now any idea how to fix! –  Jun 28 '12 at 00:05
  • @gilly3if (lastChecked.length && this.value != lastChecked[0].value) { $(this).prop("checked", false) alert("the last box you checked has a different value"); –  Jun 28 '12 at 00:07
  • i tried adding the following line after the alert displays $(this).value=lastChecked[0].value but this did nothing –  Jun 28 '12 at 00:30
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>
Mike Robinson
  • 24,971
  • 8
  • 61
  • 83
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

jackwanders
  • 15,612
  • 3
  • 40
  • 40
  • ? –  Jun 27 '12 at 20:23
  • try this whats going on jsfiddle.net/thetylercox/gy8EQ/2 –  Jun 27 '12 at 20:30
  • if i select the first box(there) and then another (here ) it works but if i select (here) and the (there) id doesnt alert –  Jun 27 '12 at 20:35
  • @tyler your jsfiddle demo is failing because the `onclick` events attached to your checkboxes isn't defined in the jsfiddle code. Try this demo: http://jsfiddle.net/jackwanders/gy8EQ/4/ It uses my solution and appears to function as you want it to – jackwanders Jun 27 '12 at 20:38
  • @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 – jackwanders Jun 27 '12 at 20:43
  • jack you are verry close but i want it to alert when diffrent! i chenger your code to != and it works from left to right but not right to left @jack –  Jun 27 '12 at 20:46
  • any idea how I could change my code work for this situation aswell –  Jun 27 '12 at 20:47
  • I want to compare the value of the last selected box to the just selected if its different alert the user –  Jun 27 '12 at 20:56
  • im confused as to why .prev() would be empty when checking 2boxes in a row regardless of the order –  Jun 27 '12 at 21:13
  • @tyler `.prev()` refers to the element's adjacent previous sibling in the DOM hierarchy. Are you trying to refer to the value of the previously selected checkbox (regardless of position in the DOM), because that would require a completely different solution – jackwanders Jun 27 '12 at 21:21
  • in that case, my suggestion would be to try again, with the understanding that to do what you want, you will need to manually maintain a reference to the last checkbox that was checked, and each time a checkbox is checked, compare to that reference. If you are still having issues, you can create a new question, but I think we've gotten too far from the nature of this question to continue here – jackwanders Jun 27 '12 at 23:47
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/

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • if i select the first box(there) and then another (here ) it works but if i select (here) and the (there) id doesnt alert –  Jun 27 '12 at 20:35
  • @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. – Cᴏʀʏ Jun 27 '12 at 20:52
  • I want to compare the value of the last selected box to the just selected if its different alert the user –  Jun 27 '12 at 20:55
  • 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 –  Jun 27 '12 at 21:02
  • @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. – Cᴏʀʏ Jun 27 '12 at 22:25
  • Your right i was completely wrong! Any idea why this will not work http://soldbybillcox.com/treasure/test3.html –  Jun 27 '12 at 23:54