简体   繁体   中英

How HTML5 input radio javascript validation works?

This question is a little weird but is playing with my head. I was looking how to verify if an input of type radio was checked/selected using JQuery.

I solved my problem using a code that looks like this:

if ($("#someId").is(":checked")) {
}

It is really simple but when I verify/inspect the input fields with the browser developer tools, none of the inputs has any attribute different, they all look the same. So:

How does the validation works? What does that function to know which of the inputs is really checked?

I will leave this Fiddle shared by @Peter J in another question so that you can see what I'm talking about and maybe help me: http://jsfiddle.net/RhnvU/

Thanks :)

This is not stored as an html attribute, but in the DOM object associated with the radio button. You can see this in devtools, in the source tab, in the watch expression pane.

在此处输入图片说明

And you can get this information in javascript:

var checkedElement= document.querySelector("input:checked");
console.log(checkedElement.checked);

http://jsfiddle.net/RhnvU/3831/

I've updated this example: http://jsfiddle.net/AlexeiTruhin/RhnvU/3829/

$('#myForm input').on('change', function() {
   alert($('input[name=radioName]:checked', '#myForm').val()); 
   console.log(document.getElementsByTagName("input")); // pure JS
});

When checking Console from Inspect Elements (in my case), we get an array of this 3 inputs. And each input has attributes. One of the attributes is 'checked', with the possible values 'true' or 'false'. This job is done by browser, so jQuery just checks this value.

If I'm not mistaken, and I'm understanding your question correctly....

When a checkbox is selected it adds the attribute checked

You can also find this by $("#someId:checked")

and in css #someId:checked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM