I am trying to assign a razor variable with the contents of a combo box on my form from within a javascript function. Like so:
<script type ="text/javascript">
<!--
function SomeFunction() {
var hours = document.getElementById("Hours");
var task = document.getElementById("TaskType_ID");
@{
var tsk = @:task.value;
}
@{
<text>
hours.value = '@ViewBag.TaskTypes.GetHours(tsk)';
</text>
}
return true;
}
//-->
</script>
the line (and every other variation I've tried)
var tsk = @:task.value;
results in an error.
As Chris pointed out, you are mixing the client and server code. The javascript is the client code, and you need the data from the server to return the value you want by using ajax calling function(get/post). Here is the snippet code of what you can do about it:
$("#tasks").change(function(){
$.get('url',$(this).val(), function(data){
// data is the hours returned from the selected task
$("#hours").val(data);
});
});
Or instead of making calls to the server everytime you select a task, you can always store the values of the tasks in a variable. Thanks
okay. here's what i wound up doing. I no longer pass in an object into the view. I added a script that binds to the change event of my first field, and then called an action in my controller via ajax and puts the result into the second field. Like so:
<script type="text/javascript">
$(document).ready(function () {
$("#q").change(function () {
$.ajax({
type: "GET",
url: "Home/Test?value=" + $('#q').get(0).value,
success: function(msg) {
$('#x').get(0).value = msg;
}
});
});
});
</script>
thank you for leading me in the right direction. With all of the razor syntax, I lost sight of the hact that this is still html. I hope you all enjoyed watching me attempt to pound a square peg into a round hole!