Undefined when selecting rel value using class

682 views Asked by At

I am using UIKit template. I have 2 buttons to toggle between. When I click on one button it will get a class uk-active. But when I try to get the rel attribute value using jQuery on form submit, it says undefined. My code is below

<button class="uk-button uk-width-1-2 uk-active" rel="0" type="button"><span class="fbaicon"></span> RENT</button>
<button class="uk-button uk-width-1-2" rel="1" type="button"><span class="fbaicon"></span> BUY</button>

And my jQuery is,

var type = $('.uk-active').attr('rel');
alert(type);

I am sure that class uk-active always exists for one of these two buttons

2

There are 2 answers

0
Akhil On

check whether code is executing before the DOM is loaded. Keep scripts in $(document).ready();

3
Akhil On

Please check the following code. It is working successfully for me.

   <html>
    <head>
    <script src="js/jquery.min.js"></script>
    <script language="Javascript" type="text/javascript">

    var type = $('.uk-active').attr('rel');
    alert("outside document ready "+type);
    $(document).ready(function(){
    var type = $('.uk-active').attr('rel');
    alert("inside document ready "+type);

    });
    </script>
    </head>
    <body>
    <button class="uk-button uk-width-1-2 uk-active" rel="0" type="button"><span class="fbaicon"></span> RENT</button>
    <button class="uk-button uk-width-1-2" rel="1" type="button"><span class="fbaicon"></span> BUY</button>

    </body>
    </html>