I have the following poorly-formed JS:
<script type="text/javascript", id="changeTabScript">
function changeTab(type) {
String.prototype.contains = function(str) {return this.indexOf(str) != -1;};
var lbl = document.getElementById('searchLabel').Value;
if (lbl.contains("Officer"))
{
type = "Officer";
}
if (type == "Officer")
$('#tab-container').easytabs('select', '#tabs1-officer');
else
$('#tab-container').easytabs('select', '#tabs1-company');
};
</script>
I have implemented Page.RegisterStartupScript("changeTab", "<script language=JavaScript>changeTab </script");,
however I haven't a clue how ClientScript.RegisterStartupScript is formed. The "key" is something I am unfamiliar with, how do I use the newer implementation?
Related
In a c# MVC project, I was given a view by a front-end designer that contains this little script:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (chosenValue == "Planning")
$('#PlanningProcess').show();
if (chosenValue == "Procurement")
$('#ProcurementProcess').show();
if (chosenValue == "Installation")
$('#InstallationProcess').show();
if (chosenValue == "Closure")
$('#ClosureProcess').show();
});
</script>
I would like to replace all the hard-coded options with a list that comes from the model. Something like this...
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
// loop over a list from the model here
if (chosenValue == " loop-item-name ")
$('# loop-item-name + Process').show();
// end loop
});
</script>
Is this possible? If so, how? And am I even going about this the right way? I was thinking I could use razor syntax, but that isn't working.
You can not compare a C# variable to a JS variable. But you can use razor to create a JS variable from a C# variable.
Here is how to fill a JS array with the values of a C# array:
#{
// fetch this from ViewModel if it needs to be dynamic
var cSharpNames = new [] { "Planning", "Procurement"};
}
<script>
var jsNames = []; // this is a JS array
#foreach(var name in cSharpNames) {
<text>jsNames.push(#name);</text>
}
</script>
Then use the indexOf() method to search in the jsNames array as has been shown by Jeremy.
I'd just make an array, check to see if the value exists within it, and if it does show it. Something like this:
<script>
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
var processes = ['Planning', 'Procurement'];
$('.ProcessDD').hide();
if (chosenValue == "")
$('#DefaultProcess').show();
if (processes.indexOf(chosenValue) > -1)
$('#' + chosenValue + 'Process').show();
});
</script>
I was overthinking this.
$('#PhaseDD').change(function () {
var chosenValue = $(this).val();
$('.ProcessDD').hide();
if (chosenValue == "")
{
$('#DefaultProcess').show();
}
else
{
$('#' + chosenValue + 'Process').show();
}
});
// Function for setting text of an element:
function setText(elementId, message)
{
'use strict';
if ( (typeof elementId == 'string')&& (typeof message == 'string') )
{
var output = $(elementId);
if (output.textContent !== undefined)
{
output.textContent = $(elementId).string;
}
else
{
output.innerText =$(elementId).string ;
}
} // End of main if.
} // End of setText() function.
I need help with this code, I need to define a function name the setText() function as shown below, when I run this code in JS Bin the page shows the code won't run, I couldn't find where the error is. Can anyone give me a hint?
Your type checking for message is unnecessary, but in case you want to keep it:
function setText(elementId, message){
if((typeof elementId == 'string') && (typeof message == 'string')){
document.getElementById(elementId).innerHTML = message;
}
}
setText("foo", "1")
setText("foobar", "2")
setText("bar", "3")
setText("barfoo", "4")
<p id="foo"></p>
<p id="foobar"></p>
<p id="bar"></p>
<p id="barfoo"></p>
You can do it using JavaScript prototypical way. This is little advanced.
HTML:
<span id="spanText"> Your sample Text </span>
First of all augment the type by this code:
/*
Augmenting type
*/
Function.prototype.addMethod = function(funcName, funcBody){
if(!this.prototype[funcName]){
this.prototype[funcName] = funcBody;
return this;
}};
String.addMethod("setText", function(text){
document.getElementById(this).textContent = text;
});
var elementId = "spanText";
elementId.setText("kkkkkkkkkkk");
Load this JS below your HTML file.
You are able to add any of your custom string, number, array method by this way.
See the complete example here:
https://jsfiddle.net/dmsbilas/wu3cd88w/
So I have been looking through relevant questions and I can't figure out exactly why my script tag is malformed.
<script language="javascript" type="text/javascript">
var showME = false;
var showSuffix = "";
#if (ViewData["showME"] != null && ViewData["showSuffix"] != null)
{
<text>
showME = #(Convert.ToBoolean(ViewData["showME"]) ? "true" : "false");
showSuffix = '#Html.Raw(Json.Encode(ViewData["showSuffix "]))';
</text>
}
</script>
EDIT!
The answer below is correct but I tracked down the malformed part to this line.
var videoHelpUrl = #(Url.Action("Index", "Help", new { Id = 46 }));
Try this:
<script language="javascript" type="text/javascript">
var videoHelpUrl = '#Url.Action("Index", "Help", new { Id = 46 })';
console.log(videoHelpUrl);
</script>
console.log will output the Url.
Note: Always keep in mind that everything following # in a Razor view will be processed by the Razor engine. This is why you can surround #Url.Action(...) with quotes. It will be processed first by Razor engine and then by Javascript when it is executed.
If you try using double {{ }} as in;
#{
if (ViewData["showME"] != null && ViewData["showSuffix"] != null)
{
<text>
showME = #(Convert.ToBoolean(ViewData["showME"]) ? "true" : "false");
showSuffix = '#Html.Raw(Json.Encode(ViewData["showSuffix "]))';
</text>
}
}
See if that works.
I tried to send a string from an html page (with javascript) to a swf file (action script 2).
i searched in google, found this page.
but the example code (version 1, not 2, you can find it in the source file .zip) didn't work in IE (IE said: object doesn't support this property or method)
where is the problem? (i don't want to use SWFObject.)
the action script :::
//From Evan Mullins # circlecube.com
//View post at http://blog.circlecube.com/2008/02/01/actionscript-javascript-communication/
import flash.external.*;
//Set up Javascript to Actioscript
var methodName:String = "sendTextFromHtml";
var instance:Object = null;
var method:Function = recieveTextFromHtml;
var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method);
//Actionscript to Javascript
//ExternalInterface.call("recieveTextFromFlash", _root.theText.text);
function recieveTextFromHtml(t) {
_root.theText.text = t;
}
_root.button.onRelease = function() {
ExternalInterface.call("recieveTextFromFlash", _root.theText.text);
_root.theText.text = "";
}
js:::
function recieveTextFromFlash(Txt) {
document.getElementById('htmlText').value = Txt;
}
and the onclick js code:::
getElementById('flash').sendTextFromHtml(htmlText.value); document.getElementById('htmlText').value = ''
Thank you.
give this javascript code a try?
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
function addToResults(results) { getFlashMovie("flashdemo").addToResults(results); }
I am working on a customvalidator to validate and replace (if possible) a postal code.
This is a Dutch postal code and should look like "5050 AA". When the user enters "5050AA" this postal code should be replaced with "5050 AA". I tried this by adding the following script to my page, which is called in the customvalidator:
<script type="text/javascript">
function Postcode_ClientValidate(source, arguments) {
var val = arguments.Value
var result = "";
var myPCRegExp1 = new RegExp("^[1-9][0-9]{3}\s?[a-zA-Z]{2}$", "i");
var myPCRegExp2 = new RegExp("(\d{4}) (\w{2})");
if ((!myPCRegExp1.test(val)) && (!myPCRegExp2.test(val))) {
arguments.IsValid = false;
} else {
if (myPCRegExp1.test(val)) {
arguments.Value = val.replace(myPCRegExp1, "$1, $2");
arguments.IsValid = true;
} else if (myPCRegExp1.test(val)) {
arguments.IsValid = true;
}
}
//jQuery("input#[HIERDEID]").val("Test");
}
</script>
However, the script above is picking up the "5038AA" but not the "5038 AA" as a match, so i can't validate a working postal code and can't rewrite to the valid postal code.
What am I doing wrong?
It's a standard .aspx page with a form and a customvalidator:
Try battling it out with this tool:
http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx for testing this sort of thing.
"5038 AA" is matching myPCRegExp1, too, because of the '\s?'
I think you need this:
var myPCRegExp1 = new RegExp("^([1-9][0-9]{3})([a-zA-Z]{2})$", "i");