Reputation: 11794
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
Reputation: 2664
Try using
var inp = "input1";
$("input[name='my"+inp+"']").val('hoera');
Upvotes: 2
Reputation: 30242
var inp = "input1";
$("input[name='" + inp + "']").val('hoera');
Which is the same as
$("input[name='input1']").val('hoera');
Upvotes: 2
Reputation: 3078
<script type="text/javascript">
$(document).ready(function () {
var inp = "input1";
$("input[name='my"+inp+"']").val('hoera');
});
</script>
Upvotes: 1
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