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

Jquery

Jquery Problem Overview


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();

Jquery Solutions


Solution 1 - Jquery

Use the name attribute selector:

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

Solution 2 - Jquery

$('[name=whatever]').val()

The jQuery documentation is your friend.

Solution 3 - Jquery

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/

Solution 4 - Jquery

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();

Solution 5 - Jquery

This works fine .. here btnAddCat is button id

$('#btnAddCat').click(function(){
		var eventCategory=$("input[name=txtCategory]").val();
		alert(eventCategory);
	});

Solution 6 - Jquery

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

Solution 7 - Jquery

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();

Solution 8 - Jquery

let startDate = $('[name=daterangepicker_start]').val();
alert(startDate);

Solution 9 - Jquery

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.

Solution 10 - Jquery

you can also use the class name.

$(".yourclass").val();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElitmiarView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryrfundukView Answer on Stackoverflow
Solution 3 - JqueryvineelView Answer on Stackoverflow
Solution 4 - JqueryAnshulView Answer on Stackoverflow
Solution 5 - JqueryAjay KumarView Answer on Stackoverflow
Solution 6 - JqueryjonesView Answer on Stackoverflow
Solution 7 - JqueryleidmarView Answer on Stackoverflow
Solution 8 - JqueryAbnormalView Answer on Stackoverflow
Solution 9 - JqueryAmira AhmedView Answer on Stackoverflow
Solution 10 - JquerycyberootView Answer on Stackoverflow