Reputation: 4496
Hello I need to pass one param to the my JS function after pressing button.
Here is my button:
<button type="button" class="btn btn-default" id="UserClick" onclick="foo(@HttpContext.Current.User.Identity.Name)">Click here to add me as a user</button>
as You can see I try to send @HttpContext.Current.User.Identity.Name
to the function foo.
Here my Foo function:
function foo(value) {
alert(value);
};
I tried sollutions from those topics: One Two
But all I get get is this error:
Uncaught SyntaxError: Unexpected token ILLEGAL
How to bypass this?
@update
All files included:
<script src="/Scripts/CreateDevice.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/jquery-1.10.2.js"></script>
full JS file:
$(document).ready(function () {
function foo(value) {
alert(value);
};
})
I can access to the js file from page-source.
Upvotes: 1
Views: 9600
Reputation: 1127
onclick="foo('@HttpContext.Current.User.Identity.Name');"
$(document).ready(function () {
window.foo = function(value) {
alert(value);
};
})
this will work...
You should consider removing the 'onclick' attribute in the html though, and binding the function to the button using jquery's .on() function.
Upvotes: 1
Reputation: 133403
First of all change you sequence of file to
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/CreateDevice.js"></script>
Declare your function outside document-ready handler. Like
$(document).ready(function () {
});
function foo(value) {
alert(value);
};
Pass your parameter in quotes
onclick="foo('@HttpContext.Current.User.Identity.Name');"
Additionally, You can bind event using .on() and pass parameter using attributes
JS
$(document).ready(function () {
//Bind Event
$(document).on('click', '#UserClick', function(){
alert($(this).data('user-name'))
});
});
HTML
<button type="button"
class="btn btn-default"
id="UserClick"
data-user-name="@HttpContext.Current.User.Identity.Name"
>Click here to add me as a user</button>
Upvotes: 2