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?
Try using
var inp = "input1";
$("input[name='my"+inp+"']").val('hoera');
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.
var inp = "input1";
$("input[name='" + inp + "']").val('hoera');
Which is the same as
$("input[name='input1']").val('hoera');
<script type="text/javascript">
$(document).ready(function () {
var inp = "input1";
$("input[name='my"+inp+"']").val('hoera');
});
</script>
精彩评论