Reputation: 67
I want to add some functionality to a button I made using the following html code:
<div>
<p style="display: inline">
Strength:  <b>@str</b>
</p>
</div>
<input class="btn btn-default" type="submit" value="Add Strength" onclick="addValue('str');"/>
When I click this button, I want to change a value I stored with Razor;
@{
int str = 5;
}
I've Googled a bit, read the documentation but I can't find anything, which works.
I made a javascript function which I called on onclick, but when I was debugging the code didn't get inside the scope of said function.
Here's the function:
function addValue(kind) {
if (ran == 0) { initialize(); }
if (left != 0) {
left--;
if (kind == "str") {
str++;
} else if (kind == "dex") {
dex++;
} else if (kind == "intl") {
intl++;
}
}
}
If anyone can explain to me how I can get some kind of function on my button I'd appreciate it.
Upvotes: 0
Views: 1347
Reputation: 628
first you need to make sure that your button go with the javascript function as you have you will have your page refreshed without knowing what happen so you need to prevent this behavior with
e.preventDefault();
in your javascript function or just change the input type to button
<input type='button' .../>
the second thing you have to notice that to change c# variable value you need some server side processing so you can use ajax.
if it's just some small thing can be done with your client side so you can add your variable to a hidden field and manupilate it with javascrip / jquery like this
<input type='hidden' id='myhiddenvar' value='@myvar'/>
and with jquery handle it like
var $myvar=$("#myhiddenvar").val();//get Value From Hidden Field
$myvar++;
$("#myhiddenvar").val(myvar);//Put Back To Hidden field
Upvotes: 0
Reputation: 1996
use hidden input field in razor to store value in html
@Html.Hidden("str",str,new {@id = "str"})
and use following javascript to retrieve and store value in str hidden field
$("#str").val("value you want to store");
var value = $("#str").val()
Upvotes: 0
Reputation: 3228
Let's say you have stored the variable within this div tag(which can be anything else):
<div id="divValue">@str</div>
And this is your button:
<input class="btn btn-default" type="submit" value="Add Strength" id="btn"/>
Using jquery:
<script>
$(document).ready(function() {
$('#btn').click(function(e){
e.preventDefault();
var textValue = $('#divValue').text();
if (textValue == "str") {
$('#divValue').text('changeText');
//or other action
} else if (textValue == "dex") {
//action
} else if (textValue == "intl") {
//action
}
});
});
</script>
Upvotes: 1