Two radio buttons share one “id”?

后端 未结 8 2163
别那么骄傲
别那么骄傲 2020-12-29 06:59

I\'m borrowing/adapting this simple html/javascript form set up to put some data in the database. The original code uses text fields in the form, but I\'m using radio button

相关标签:
8条回答
  • 2020-12-29 07:30

    you must assign same name but different id to input type=radio because this is basic property of raido button that you need to select only one value from givel aal radio buttons.

    but that id should not be assigned to other form elements

    0 讨论(0)
  • 2020-12-29 07:32

    Do not repeat id's.It is best practice to use only one id per page as it must be unique.You can group the radio buttons using name attribute.

    use $('input[name=interview]') to get the value.

    0 讨论(0)
  • 2020-12-29 07:39

    ID Attribute is unique across the page. You should have different Ids for each radio button. Use below code to get the input value.

    var inputUser=$('input:radio[name=interview]:checked').val();
    
    0 讨论(0)
  • 2020-12-29 07:45

    Since you are using jQuery you can easily get the value of the selected radio button by using the :checked selector:

    $("input[name=interview]:checked").val()
    

    You should definitely not give more than one element the same ID (that's invalid HTML and will lead to confusing bugs in your JavaScript), but even if that worked it wouldn't help in this case since radio buttons as a group don't have a selected value: you need to determine which one is currently checked and then get its value as shown above. (This is not a problem when getting the value on the webserver when the form is actually submitted, because only the value from the checked radio gets submitted.)

    Note also that in your original code where you said inputUser.attr("value"), you could've said inputUser.val().

    0 讨论(0)
  • 2020-12-29 07:47

    If want to use pure javascript you have to use..

    document.querySelector('input[name=radio_btn_name]');
    

    but it need updated browser. Old browsers may result incorrect.

    To overcome this issue, javascript library is to use (library will handle the issue). For this use the following..

    $('input[name=radio_btn_name]:checked').val();
    
    0 讨论(0)
  • 2020-12-29 07:50

    The id assigned to an element must be unique within the document. So, no, you should not use the same id.

    0 讨论(0)
提交回复
热议问题