How to get a value of an element by name instead of ID

前端 未结 10 900
予麋鹿
予麋鹿 2020-12-07 11:53

How could I get the value of an element via the attribute name instead of the ID. eg if I use by id it would be $(\'#id\').val();

相关标签:
10条回答
  • 2020-12-07 11:54

    This works fine .. here btnAddCat is button id

    $('#btnAddCat').click(function(){
            var eventCategory=$("input[name=txtCategory]").val();
            alert(eventCategory);
        });
    
    0 讨论(0)
  • 2020-12-07 11:56
    //name directly given
    <input type="text" name="MeetingDateFrom">
    var meetingDateFrom = $("input[name=MeetingDateFrom]").val();
    
    //Handle name array
    <select multiple="multiple" name="Roles[]"></select>
     var selectedValues = $('select[name="Roles[]"] option:selected').map(function() {
        arr.push(this.value);
      });
    
    0 讨论(0)
  • 2020-12-07 11:57

    To get the value, we can use multiple attributes, one of them being the name attribute. E.g

    $("input[name='nameOfElement']").val();
    

    We can also use other attributes to get values

    HTML

    <input type="text" id="demoText" demo="textValue" />
    

    JS

    $("[demo='textValue']").val();
    
    0 讨论(0)
  • 2020-12-07 11:57

    Only one thing more: when you´re using the "crasis variable assignment" you need to use double cotes too AND you do not need to use the "input" word!:

    valInput  = $(`[name="${inputNameHere}"]`).val();
    
    0 讨论(0)
  • 2020-12-07 12:03

    Use the name attribute selector:

    $("input[name='nameGoesHere']").val();
    

    It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/

    0 讨论(0)
  • 2020-12-07 12:05

    Use the name attribute selector:

    $("input[name=nameGoesHere]").val();
    
    0 讨论(0)
提交回复
热议问题