Why won't function output into this jQuery selector?

I'm hoping this is something silly I've done. I got a function unigref near the bottom, which (I believe) outputs a string. However, when I call the function to build a jQuery selector, I can't get it to work properly. I know that everything else works because when I use a static string the radio button is selected.

Here's my jsfiddle/9Edxx. Please help.

var checkCount = 0;
var maxChecks = 2;

$(document).ready(function() {

$("#test").click(function() {
    alert($(':checked').length);
});

$(':checkbox[name=checkbox]').change(function() {


    checkCount = $(':checkbox:checked').length;

    if (checkCount >= maxChecks) {
      $(':checkbox[name=checkbox]').not(':checked').attr('disabled', true);  
        $(":radio[value="+uniqref()+"]").prop('checked', true);


    } else {
      $(':checkbox[name=checkbox]:disabled').attr('disabled', false);
    }

    if (this.checked) {
        $("td.label").append("<label>" + this.value + "</label>");
    } else {
        $("td.label").find(":contains('" + this.value + "')").remove();
    }

});

$('#button').click(function() {
    alert(uniqref());
});


function uniqref() {
    return $("td.label").text().split('').sort().join('').replace(/\s/g, "");
}


});​

UPDATE: The typo has been correct, but the problem still exists.

http://jsfiddle.net/9Edxx/

Upvotes: 0

Views: 101

Answers (3)

mari
mari

Reputation: 234

No need for hack. http://jsfiddle.net/dn7gM/

p.s.: only works for the 2 first radios, since not all ids are setted correctly ;-)

Upvotes: 1

Niko
Niko

Reputation: 26730

Yeah it's really silly: It's just a typo.

$(":radio[value="+unigref()+"]").prop('checked', true);

should be

$(":radio[value="+uniqref()+"]").prop('checked', true);

with a lowercased Q instead of a G.


Also, you're calling uniqref() before actually updating the value of td.label.

Should be in this order:

if (this.checked) {            
    // ...
}

if (checkCount >= maxChecks) {            
    // ...
}

http://jsfiddle.net/7mvmT/7/

Upvotes: 9

wroniasty
wroniasty

Reputation: 8052

http://jsfiddle.net/7mvmT/6/

Basically this line:

$(":radio[value="+uniqref()+"]").prop('checked', true);

is called prematurely (before the checkbox is actually checked. A simple, ugly hack:

setTimeout(function(next) {               
     $(":radio[value="+uniqref()+"]").prop('checked', true);    
}, 0);

solves it.

Also you had a typo as Niko mentioned.

Upvotes: 4

Related Questions