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

Viewed 421794

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 Answers

Use the name attribute selector:

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

The jQuery documentation is your friend.

//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);
  });

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();
let startDate = $('[name=daterangepicker_start]').val();
alert(startDate);

What element is used for the part with a green background? Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.

Related