简体   繁体   中英

How to acquire the "value" attribute of an <input> element in html?

Suppose there is an <input> element. When I use jQuery to acquire the attributes of this element, following is my code:

 console.log($("#radio").attr("type")); console.log($("#radio").attr("value"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="radio" type="radio" value="a" />

and the result is: radio undefined

why can't I acquire the "value" attribute?

Converting my comments to answer for the sake of posting examples

$("#radio").val() is the normal way.

Do NOT have TWO radios with the same ID. IDs must be unique

Radios must have the same NAME so a click on one will remove the checked from the other.

You can get the value of the checked named radio as $("[name=radio]:checked").val()

Here I on purpose leave the duplicate IDs and you will see it gets the value of the first only when accessed via ID

It is not possible to get undefined in this setup unless you call the script before the radios exist

You might want to wrap in a load event handler in case the radios are not available in the DOM when your script runs

 $(function() { // when page loads console.log($("#radio").val()) console.log($("#radio").attr("value")); console.log($("[name=radio]:checked").val()) $("[name=radio]").on("click", function() { console.log(this.value, $(this).val()); // either will work }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="radio" name="radio" type="radio" value="b" /> <input id="radio" name="radio" type="radio" value="a" 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