Paschalidis Christos
Paschalidis Christos

Reputation: 452

Best way to get the 'id' from an input element if knowing the 'name' of it

this is jquery based question.

Lets say that I have the following form.

<form id="add_some_love_form">
    <input type="hidden" name="csrfmiddlewaretoken" value="blahblah">

    <input type="hidden" name="validate" value="True">

    <label for="product_number_field">SOME LABELS:</label>
    <input id="product_number_field" name="number" type="text">

    <label for="product_name_field">SOME LABELS:</label>
    <input id="product_name_field" name="name" type="text">

    <label for="product_group_field">SOME LABELS:</label>
    <select id="product_group_field" name="product_group">
        <option value="" selected="selected">---------</option>
        <option value="1">blah 1</option>
        <option value="2">blah 2</option>
        <option value="3">blah 3</option>
    </select>
</form>

Is it possible that I can get the id of the input element with

if the only thing I know for this element is that the name of it is 'number' and has an input tag?

Upvotes: 2

Views: 933

Answers (2)

eisbehr
eisbehr

Reputation: 12452

Just select the element by attribute name and get the id with attr.

var id = $("input[name=number]").attr("id");

Example:

console.log($("input[name=number]").attr("id"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_number_field" name="number" type="text">

Upvotes: 4

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

Try this:

$('input[name="tag_name"]').attr('id');   // it will return id

Upvotes: 1

Related Questions