Reputation: 378
I am having some trouble with variables in javascript and asp.net mvc project.
I am building an app where the user has the option to display a page in full-screen format.
When the user wants to display a page in full screen format and click the submit key they should get a warning before the page is submitted.
I am having some problems with the javascript that handles the condition if the user should get a warning or not however. The following code illustrates the problem:
Javascript:
<script type="text/javascript">
var $full = false; //initiates the full variable
$(document).ready(function () {
$("#TemplateID").change(function () { //when selected index of dropdown is changed
var selectedIndex = $("select option:selected").first().text(); //the selected index
$.get('@Url.Action("getIfFullscreen", "Messages")', //calls an ASP.net method to determine if selected index should be displayed as fullscreen
{ id: selectedIndex }, function (data) {
$full = data; //sets the variable full to return value
Debug.writeln("onchange:" + $full) //displays as expected
});
});
});
$(document).ready(function () {
$('[data-confirm]').click(function (e) {
Debug.writeln("onclick:" + $full); //displays as expected
if ($full == true){ //always takes the value from when the variable full was initiated
if (!confirm($(this).attr("data-confirm"))) {
e.preventDefault();
}
}
});
});
</script>
HTML:
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" data-confirm="Are you sure?" value="Skicka" class="btn btn-default" />
</div>
</div>
It seems like the variable full is changed (in the first function) from the look of the debug output but the if statement always interprets it as it was first initiated.
I am quite new to javascript and any help is greatly appreciated.
Upvotes: 0
Views: 67
Reputation: 218722
If your server code is returning a boolean true value, It will come as True
, not true
. In javascript True
is not boolean true
. So your js variable is going to be overwritten with the string value "True"
So you may change your if condition to check against the string value
if ($full === "True"){ }
Upvotes: 1