Ahmet
Ahmet

Reputation: 115

How can I change element attribute with $("this").change?

Edit: Thank you all for your suggestions. I've made suggested changes on my question. I edited the code, no syntax errors anymore, I get no errors from browser anymore.

This is the problem I'm dealing with now: I get the alert message "null" in each perform.

I've been trying to change the value of an element with a checkbox, make the value "1" or "0" for a number of reasons. To check if I was successful, I placed an alert() inside the code to get the changed attribute. Whether I check or uncheck the checkbox, I only get "undefined" message. I think I'm messing up with synchronization but I don't know how.

$(document).ready(function() {
  
$("#checkTabsence").change(function(){
    if($(this).is(':checked'))
    {
        var tutorPresence = document.getElementById("tutorCheckEl");
            tutorPresence.setAttribute = ("href", "1");
        var alertme = tutorPresence.getAttribute("href");
        alert(alertme)
    }
    else
    {
        var tutorPresence = document.getElementById("tutorCheckEl");
            tutorPresence.setAttribute = ("href", "0");
        var alertme = tutorPresence.getAttribute("href");
        alert(alertme)
    }    


});
  });
<html>
<input type="checkbox" id="checkTabsence">
<a id="tutorCheckEl" style="display:none;"></a>
</html>

Upvotes: 0

Views: 89

Answers (2)

Dave
Dave

Reputation: 10924

You've got a few problems:

  1. You're trying to call .attr() on a plain DOM element but .attr() is a jQuery function. Either call setAttribute() on the DOM element, or use jQuery instead of getElementById.
  2. You're forgetting the jQuery ID selectors need to be prefixed with a #. Change $("tutorCheckEl") to $("#tutorCheckEl").
  3. If you are going to use .attr() in jQuery, the syntax to set an attribute is tutorPresence.attr("value", "1")
  4. If you are going to use setAttribute(), the syntax to set an attribute is tutorPresence.setAttribute("value", "1")

Upvotes: 2

Alex McMillan
Alex McMillan

Reputation: 17952

The problem is that $("tutorCheckEl") matches against a <tutorCheckEl> which I doubt you have on the page.

Did you perhaps mean to use $("#tutorCheckEl"), which would match <a id="tutorCheckEl"> (or indeed any element with id="tutorCheckEl") ?

Also, an anchor tag (<a>) has no value attribute. value is for input-type elements.

Upvotes: 1

Related Questions