0

I have this javascript code:

var right = document.getElementById("true").checked;
var wrong = document.getElementById("false").checked;

if (right){
    answer += 100;
}

I want to replace the Javascript with jQuery, so I replaced this line:

var right = document.getElementById("true").checked;

with this:

var right = $('#true')[0].attr('checked');  

I have also downloaded and added the jQuery file to my HTML:

<script src="jquery-1.11.2"></script>

However when I replaced the above JS code with jQuery it isn't working at all. What am I doing wrong ?

EDIT: I have also tried this,

function calc(){
    $(function() {
        var isTrue = $('#true').attr('checked');    
    });

    var wrong = document.getElementById("false").checked;

    if (right){
        answer += 100;
    }
}

But it is still not working.

4 Answers 4

3

The problem is that the [0] accessor on the jQuery object returns the native DOMElement. This does not have an attr() method, so if you checked the console you'd most likely see an error.

In your case you should instead just call attr() (or better yet, prop()) on the object resulting from the selector. Also, don't forget to wrap your code in a document.ready handler. Try this:

$(function() {
    var right = $("#true").prop('checked');
    var wrong = $("#false").prop('checked');

    if (right){
        answer += 100;
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Can you tell OP why he should use .prop instead of .attr? api.jquery.com/prop
@Rory, Should I just create this jquery function inside Javascript function ? Like i showed in my question ? (please see the edit)
@RileyWillow ah, if you are executing your code from a function, you do not need the $(function() { }) wrapper.
1

When using jQuery 1.9+ the attr('checked') gets the initial state of the checkbox when its state changes you need to use the prop() function.

$('#true').prop('checked');

Comments

1

ID is unique identificator. You should have only one unique ID in your HTML. That means, you don't need to put there array identificator. Do it like this:

var right = $('#true').attr('checked');

Comments

1

Try

var right = $('#true').attr('checked');  

instead of

var right = $('#true')[0].attr('checked');  

and you should use

var right = $('#true').prop('checked');  

because $('#true')[0] returns you the DOM element and .attr() works with jQuery object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.