I want to make a Jquery Selector based on the value of an input field. And this should be dynamically with a C# Variable:
<script type="text/javascript">
$(function () {
var company = @ViewBag.company;
$("input[value='"+ company +"']").attr("checked", "checked");
});
</script>
Somehow its always give me an error. Further Info: The ViewBag Variable is sometimes something like: "Bank of Scotland". so it has withspace in it. Is this the problem? EDIT: The Error is something like "missing ';' in statement" on the first line of the ready function.
I have in my HTML then a radio button with the value "Bank of Scotland" and And the ViewBag Variable is "Bank of Scotland" as well. When I just hardcode this it works:
$("input[value='Bank of Scotland']")[...more code...]
Does anyone know, how to fix this? Thx for your help :)
Just write:
var company = '@(ViewBag.company)';
In your example output will be (with your code):
var company = Bank of Scotland;
which is not valid js...
Just change this line
var company = '@ViewBag.company';
And it should be like this
$(function () {
var company = '@ViewBag.company';
$("input[value='"+ company +"']").attr("checked", "checked");
});
For me, I never directly assign C# code to JavaScript variable, because I want to separate C# and JavaScript.
I set the Viewbag value to hidden field. Then I retrieve from jQuery like this.
$('.hidden-field').val()
Or you can directly assign like this:
var data = "@ViewBab.value";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.