Reputation: 7
How do I get the value of a name attribute which contains a period through a variable:
I have the following example:
<input type="text" value="Hello!" name="input.hi" />
<input type="text" value="Goodbye" name="input.bye" />
<input type="button" data-get-value="input.hi" value="Arrive" class="greet" />
<input type="button" data-get-value="input.bye" value="Leave" class="greet" />
<script>
$(".greet").click(function() {
var str = $(this).attr("data-get-value").replace(/\./g, '\\\\.');
var input = $("[name=" + str + "]").val();
alert(input);
});
</script>
The error I am getting is:
Uncaught Error: Syntax error, unrecognized expression: [name=input\\.hi]
But if I run the command through my console as follows:
$("[name=input\\.hi]").val();
or
$("[name=input\\.bye]").val();
It returns the correct value.
I did searching on this board to find out how to escape the period and how to access it, but I can't get this final step to work.
Note: I cannot use another attribute like ID - it has to be name
Upvotes: 0
Views: 58
Reputation: 11328
You can do it on this way:
$(".greet").click(function() {
var str = $(this).attr("data-get-value");
var input = $("[name='" + str + "']").val();
alert(input);
});
Just escape dot with single quotes, no need for replace...
Upvotes: 2