The difference between [object Object] and [HtmlDivElement]. Div game with jQuery

I use divs as radio buttons and ask a question.

I declare a function and a variable like this

I have two styles installed: .buttonUp and .buttonDown, which will be applied to the onclick div event.

<script type="text/javascript"> var onCheck; function setRadio(param_ElementRef) { if (param_ElementRef != onCheck) { if (onCheck) { onCheck.className = 'buttonUp'; } param_ElementRef.className = 'buttonDown'; onCheck = param_ElementRef; } } </script> 

I call a function in a div like this

 <div id="Yes" class="buttonUp" onclick="setRadio(this)">Yes</div> <div id="No" class="buttonUp" onclick="setRadio(this)">No</div> <div id="Maybe" class="buttonUp" onclick="setRadio(this)">Maybe</div> 

This works fine, but it's hard for me to set the default value for the onCheck variable.

I tried to provide an id div, but when I alert($('#Yes') displays [object Object] , whereas if I alert(param_ElementRef) displays [object HtmlDivElement]

Obviously, there is a difference between the two, and is there a way to return the same object via an id or similar link?

Many thanks

+4
source share
2 answers

Reason alert($('#Yes') shows [object Object] because it is a jQuery object.

On the other hand, if you want [object HtmlDivElement] return, try alert(document.getElementById('Yes')) instead of alert($('#Yes'))

You can also get a simple js object from a jQuery object using get()

eg. alert ($ ('# Yes')) displays [object Object] and if you try alert($('#Yes').get(0)) you will get [object HtmlDivElement]

+4
source

Add an extra class to the div for the option

 <div id="yes" class="button buttonUp">Yes</div> <div id="no" class="button buttonUp">No</div> <div id="maybe" class="button buttonUp">Maybe</div> 

Here is jQuery code to select an option

 var option; $('.button').click(function() { option = $(this).attr('id'); $('.selected').html('Your option - ' + option); $(this).addClass('buttonDown').removeClass('buttonUp'); });​ 

Check the sample code in jsFiddle http://jsfiddle.net/prasofty/zWjjk/

+2
source

Source: https://habr.com/ru/post/1402413/


All Articles