Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Monday, March 11, 2024

Convert String to Title case using Javascript

Here is the function to convert string to title case, which can handle spaces and underscores. Below function will remove underscores from the string.

// Import the function
function convertToTitleCase(input) {
  return input.toLowerCase().replace(/_/g, ' ').replace(/\b\w/g, function(match) {
    return match.toUpperCase();
  });
}

You can call the convertToTitleCase function in HTML by including a script tag with the function definition, and then using JavaScript to call the function and display the result.

Here's an example of how you can call the convertToTitleCase function in HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Convert to Title Case</title>
</head>
<body>

<p id="output"></p>

<script>
// Function definition
function convertToTitleCase(input) {
  return input.toLowerCase().replace(/_/g, ' ').replace(/\b\w/g, function(match) {
    return match.toUpperCase();
  });
}

  // Call the function and display the result
  let input = "Nagasai_Srinivas_Mudara";
  let convertedString = convertToTitleCase(input);
  document.getElementById("output").innerHTML = convertedString;
</script>

</body>
</html>

In this JavaScript function, the replace method is used with a regular expression to match the underscores and lowercase letters and convert the lowercase letters to uppercase when preceded by an underscore or at the beginning of the string.

You can use the convertToTitleCase function to convert any input string to title case in a generic and reusable way.

Thursday, July 13, 2023

How to read JSON list from JavaScript

To read a list of JSON objects in JavaScript, you can use the JSON.parse() function to parse the JSON string into a JavaScript object or an array.

Here's an example:

var jsonString = '[{"name":"Maximus","age":30},{"name":"Peter Parker","age":25},{"name":"Bob Krammer","age":40}]';

// Parse the JSON string into an array of objects
var jsonArray = JSON.parse(jsonString);

// Iterate over the array and access the properties of each object
for (var i = 0; i < jsonArray.length; i++) {
  var obj = jsonArray[i];
  console.log("Name: " + obj.name + ", Age: " + obj.age);
}
  

In the above example, the jsonString variable holds a JSON string representing an array of objects. The JSON.parse() function is used to parse the JSON string into the jsonArray variable, which becomes an array of objects.

You can then iterate over this array and access the properties of each object as shown in the for loop.

Note that the JSON string should be well-formed, with double quotes around property names and string values.

Hope this helps!

Monday, May 28, 2018

“md-select” - How to set a selected option of a dropdown list control using angular JS?

Try this following code to set selected value based on selected index.

<div layout="row" flex layout-align="start">
	<md-input-container flex>
		<label>{{'TicketType_Label'| translate}}</label>
		<md-select ng-model="feedbackObj.ticketType"  ng-required="true" md-no-asterisk="false" >
			<md-option ng-selected="i == 0 ? true:false"  ng-repeat="(i,type) in TicketTypes" >{{type}}</md-option>
		</md-select>					
	</md-input-container>
</div>

Thursday, October 05, 2017

javascript - .includes() not working in Internet Explorer

includes is not supported in Internet Explorer (or Opera)

Instead you can use indexOf. #indexOf returns the index of the first character of the substring if it is in the string, otherwise it returns –1

or you can use below function to in your javascript and you can still use include to work in IE10 / IE11

//IE 10/IE11 fix for includes function
String.prototype.includes = function () {
    'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
};

Hope this helps!

Sunday, August 28, 2016

Flip image via Javascript/CSS?

This is how image can be flipped, like a mirror image

<div id="container" class="flip-vertical">
<h3 class="flip-vertical">vertical flip</h3>
</div>

.flip-horizontal {
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
    -ms-filter: fliph; /*IE*/
    filter: fliph;
}
.flip-vertical {
    -moz-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    transform: scaleY(-1);
    -ms-filter: flipv; /*IE*/
    filter: flipv;
}

Sunday, June 05, 2016

Browser support and comparisons

Recently found a amazing site www.caiuse.com which is Useful to web designers/developers.

"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.

Very useful and I recommend this!

Tuesday, November 17, 2015

TextBox set to ReadOnly using javascript

Here is a quick solution that works across the all browsers. Add below code in input textbox.

onKeyPress = "javascript: return false;" onPaste = "javascript: return false;" .

That way, even the textbox is enabled, the user will not be able to modify the data

Thursday, September 11, 2014

How To Display Current Time on Page using Javascript

Here is the JavaScript function which will get current time in Military format.

<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('Showtime').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}

function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>

Thursday, March 27, 2014

How to change or add script tag source from C#?

Here is how we can add script to page header from code behind in c#. The reason why I am doing this is I have these JavaScript files included in master page. And when I try to give path of these files I am getting issues with absolute page when I got to other pages since I have these in master page.

and one more reason why I did is I don’t want to change this every time if deploy to different environment from QA, Stage and Production.

This is how we can do it in your master page.

string js1 = HttpContext.Current.Request.ApplicationPath + "/Scripts/jquery.cycle2.js";
string js2 = HttpContext.Current.Request.ApplicationPath + "/Scripts/jquery.countdown.js";

Literal js1script = new Literal();
js1script.Text = string.Format(
@"<script src=""{0}"" type=""text/javascript""></script>", js1);
Page.Header.Controls.Add(js1script);

Literal js2script = new Literal();
js2script.Text = string.Format(
@"<script src=""{0}"" type=""text/javascript""></script>", js2);
Page.Header.Controls.Add(js2script);

Hope this is useful!!

Friday, January 10, 2014

How to hide all Validators from JavaScript in .NET?

Here is how you can hide all validator messages from below JavaScript.  

function HideValidators() {
if (window.Page_Validators)
for (var vI = 0; vI < Page_Validators.length; vI++) {
var vValidator = Page_Validators[vI];
vValidator.isvalid = true;
ValidatorUpdateDisplay(vValidator);
}
}

Tuesday, January 07, 2014

How to hide Validation controls from JavaScript in .NET?

Here is how you can hide validation summary using the below JavaScript.  Call this in your aspx page. This should do trick for you.

// Hiding all validation contorls  
for (i = 0; i < Page_Validators.length; i++) {
ValidatorEnable(Page_Validators[i], false)
}


It works in IE and Mozilla. Hope this helps

Thursday, October 24, 2013

How to hide Validation Summary from JavaScript in .NET?

Here is how you can hide validation summary using the below JavaScript.  Call this in your aspx page. This should do trick for you.

function HideValidationSummary(){

if (typeof(Page_ValidationSummaries)!= "undefined"){ //hide the validation summaries
for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
summary = Page_ValidationSummaries[sums];
summary.style.display = "none";
}
}

}

It works in IE and Mozilla. Hope this helps

 

Sunday, December 05, 2010

Javascript Tip: Close Pop-up - Refresh Parent

Sometimes we need to force parent refresh on closing pop-up window which was opened from this parent window. There are many ways to make it work, however the most elegant way will be using location.href

function Refresh() 
{
    window.opener.location.href = window.opener.location.href;
    window.close();
}

Smile

Tuesday, November 16, 2010

Help full Tools and Converters

Here are some useful tools and converters which are helpful for conversion and compression

.NET Code converters

You can translate any C# code to VB.NET and VB.NET to C#.

http://converter.telerik.com/

http://www.aspalliance.com/aldotnet/examples/translate.aspx

http://www.developerfusion.com/utilities/convertcsharptovb.aspx

I have used first URL from telerik. Its works just great

Compress your CSS

http://www.developerfusion.com/tools/compresscss/

Compress and obfuscate javascript

http://www.developerfusion.com/tools/compressjavascript/

Clear Browser History Through Javascript

If you need to clear the Browser History, after arriving on a particular page (e.g. arriving to Login page after Logout).

Here is the code to do this. If you put this code in Login page, it wont take it to be back page. You need to put this from where you do not want to move back. Here is the code snippet.

<script type="text/javascript">
        window.onload = function () { Clear(); }
        function Clear() {            
            var Backlen = history.length;
            if (Backlen > 0) history.go(-Backlen);
        }
</script>

if you do not want the user to move to the back page, you can do as below. This script needs to be repeated at where you don’t want to do this.

<script type="text/javascript">
       if(window.history.forward(1) != null)
           window.history.forward(1);
</script>

Hope this helps.

Monday, October 04, 2010

JavaScript: Display Clock

Displaying a clock is very similar to making a countdown timer. All we have to do is to create a new date and get it's hours, minutes, and seconds.

Here is a example:

<!-- This span is where the clock will appear -->
<div id='clockDiv'></div>
<script type="text/javascript">
function clock() {
   var now = new Date();
   var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
   document.getElementById('clockDiv').innerHTML=outStr;
   setTimeout('clock()',1000);
}
clock();
</script>

Hope this helps :-)

JavaScript: Count down Timer

This is how creating Count down timer using JavaScript with Julian dates. This code below creates two Julian dates, now and newYear. By subtracting now from newYear we get an integer which represents the difference between the two dates.

Suppose you want to know your birthday in days, hours and minutes etc. This is how you can achieve using JavaScript.

<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>
<script type="text/javascript">
// Here's our countdown function.
function happyBirthDay() {
var now = new Date();
var newYear = new Date('October 20, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);   
    diff=diff/1000;            
var seconds=Math.floor(diff % 60);
    diff=diff/60;
var minutes=Math.floor(diff % 60);
    diff=diff/60;
var hours=Math.floor(diff % 24);
    diff=diff/24;
var days=Math.floor(diff);
// We'll build a display string instead of doing document.writeln
   var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
       outStr+= ' minutes, ' + seconds + ' seconds until your birthday!'; 
   // Insert our display string into the countdown span.
   document.getElementById('countdown').innerHTML=outStr;
   // call this function again in exactly 1 second.   
   setTimeout("happyBirthDay()",1000);
}
// call the countdown function (will start the timer)
happyBirthDay();   
</script>

Hope this helps!

Thursday, July 29, 2010

How to: Javascript Loading Conditionally for IE

Loading Javascript conditionally for IE. When rendering fixes are needed for IE, you can enclose CSS, JavaScript, or HTML markup in conditional comment tags directed at one or more versions of IE with an "if" statement; IE will then execute the code specified within them, while all other browsers treat them as standard comment tags and ignore them. The "if" statement must reference IE in square brackets as shown below; in this example include script only for IE

<!--[if IE]>
    <script type="text/javascript">
        /*  Do Stuff */
    </script>
<![endif]-->
below example shows how to exclude a script block from IE:
<![if !IE]>
    <script type="text/javascript">
        /*  Do Stuff */
    </script>
<![endif]>
Conditional comments can also be targeted to a particular version of IE, or a subset of versions, like those released prior to IE7 or IE6
<!--[if lt IE 7]>
  <link rel="stylesheet" type="text/css" href="ie_fixes.css" />
<![endif]-->

Hope this helps!

Tuesday, February 17, 2009

JavaScript - Confirm OK Cancel - Yes No

just cam across a post, brilliant way to change the confirm box from ok / cancel to yes / no.

Well it doesn't work in Mozilla though, it returns ok / cancel only

http://www.delphifaq.com/faq/javascript/f1172.shtml

<script language=javascript>

/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)

function window.confirm(str)
{
execScript('n = msgbox("'+str+'","4132")', "vbscript");
return(n == 6);
}

@end @*/
var r = confirm("Can you do it?");
alert(r);
</script>