user603007
user603007

Reputation: 11794

Is it possible to select an element with jQuery using a variable?

I am trying to assign a value in jQuery to an input field with a variable name.

Basically I want to access inputs depending on the name of the input:

  <script type="text/javascript">

    $(document).ready(function () {

        var inp = "input1";
        $("input[name='my<%inp%>']").val('hoera');
    });

</script>

But this does not work. Does anyone have an idea?

Upvotes: 3

Views: 79

Answers (4)

Try using

var inp = "input1";
$("input[name='my"+inp+"']").val('hoera');

Upvotes: 2

Majid Fouladpour
Majid Fouladpour

Reputation: 30242

var inp = "input1";
$("input[name='" + inp + "']").val('hoera');

Which is the same as

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

Upvotes: 2

Carls Jr.
Carls Jr.

Reputation: 3078

<script type="text/javascript">

    $(document).ready(function () {

        var inp = "input1";
        $("input[name='my"+inp+"']").val('hoera');
    });

</script>

Upvotes: 1

StuperUser
StuperUser

Reputation: 10850

You can concatenate the string to build the selector:

var inputName = 'name';
$('input[name="' + inputName + '"]').val('hoera');

This is because the string is passed as a parameter to the jQuery function (that has an alias of $), so it doesn't really matter how the string is built by the time it gets passed in.

Upvotes: 2

Related Questions