G43beli G43beli - 6 months ago 23
jQuery Question

How can I use c# ViewBag variable in Jquery Selector?

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 :)

Answer

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");
 });
Comments