JavaScript watermark with alternating/dual mode

In the following code snippet, I have implemented a function to make window.status switch between displaying "a" and "b."

function alternateViaIntrvl() {
    setInterval('alterStatus()', 500);
}
var altrCounter = 0;

function alerted() {
    var txt = "a";
    if (altrCounter % 2 == 0) {
        txt = "b"
    }

    window.status=txta;
    countalerted++;
}

Initially, I attempted to create an alternating Ajax watermark that switched between displaying "insert date" and "mm/dd/yyyy." However, this became too complex when trying to access Ajax with JavaScript.

To achieve this effect, I utilized the set_Text("mm/dd/yyyy") method.

Upon further exploration, I came across an alternative solution to Ajax: javascriptWaterMark by Md.Asaduzzaman Azad.

I then attempted to incorporate a setInterval() function into the existing code base in order to create a dual-mode JavaScript Watermark functionality.

While the implementation seemed straightforward, akin to the example showcasing the alternation of window.status, I struggled to replicate the same behavior for my specific use case.

The following snippet illustrates the JavaScript functions Focus and Blur:

 function Focus(objname, waterMarkText) {
        // Function logic here
}



 function Blur(objname, waterMarkText) {
        // Function logic here
}
  • html

    <table>
        <tr>
            <td>
                User Id
            </td>
            <td>
                <asp:TextBox ID="txtUserId" runat="server" 
            onfocus="Focus(this.id,'insert date')"
                onblur="Blur(this.id,'insert date')" 
                Width="126px" CssClass="WaterMarkedTextBox">
                insert date
               </asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                <asp:TextBox ID="txtPwd" TextMode="Password" runat="server" 
                        onfocus="Focus(this.id,'')"
                    onblur="Blur(this.id,'')" Width="126px" 
                      CssClass="WaterMarkedTextBoxPSW" />
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Submit" />
            </td>
        </tr>
    </table>
    </form>

This is essentially a hidden table row that remains invisible by default, only becoming visible upon clicking an image button event in the Codebehind.

   TRinsertForm.Style.Add("visibility", "visible");

As a potential workaround, I considered running a script from the code behind to generate JavaScript code that could set the initial text for the textbox or perform other actions as needed.

Answer №1

Here is the custom code I developed:

Check out the HTML code below to implement a perfectly alternating Watermark using a combination of JavaScript and AJAX methods.

var original = "insert date";
var alternate = "mm/dd/yyyy";
var masked = "__/__/____";
var countalerted = 0;
var txt = "";
var intird = 0;
if (intird == 0) {
    intrId = setInterval(function () { alterWaterMarkForDateTBX() }, 1000);
}
function SetIntervalTBX() {
    setInterval(function () { alterWaterMarkForDateTBX() }, 1000);
}

function alterWaterMarkForDateTBX() {
    var d = new Date();
    var t = d.toLocaleTimeString();

    if (countalerted < 4) {
        if (countalerted % 2 == 0) {
            document.forms["form1"].elements["TBXinsertDate"].value = original;
        }
        else {
            document.forms["form1"].elements["TBXinsertDate"].value = alternate;
        }
        countalerted++;
    }
    else {
        window.status = intrId;
        clearInterval(intrId);
//        document.forms["form1"].elements["TBXinsertDate"].value = original;
    }
}




var wasFocused = false;var wasBlur = false;
function Focus(objname, waterMarkText) {
    wasFocused = true;
    if (wasBlur == false) {
        obj = document.getElementById(objname);
        if (obj.value == masked) {
            obj.value = ""; obj.removeAttribute("title");
            obj.className = "NormalTextBox";
            if (obj.value == original || obj.value == alternate || obj.value == "" || obj.value == null) {
                obj.style.color = "black";
            }
        }
    }
    else 
    {


            obj.value = "";

    }
}


function Blur(objname, waterMarkText) {


    var alternateWM1 = "insert date";
    var alternateWM2 = "mm/dd/yyyy";
    obj = document.getElementById(objname);

    if (obj.value == "" || obj.value == masked) {
        obj.value = waterMarkText;
        obj.className = "WaterMarkedTextBox";
        wasBlur = true;
    }
    else {
        obj.className = "NormalTextBox";
    }
    if (wasBlur == false) {
        if (obj.value == original || obj.value == alternate || obj.value == "" || obj.value == null ) {
            obj.style.color = "black";
            wasBlur = true;
            if (wasFocused == true) {
                SetIntervalTBX();
            }
        }
    }
}



         <asp:TextBox ID="TBXinsertDate" runat="server" ToolTip="insert date" 
        CssClass="WaterMarkedTextBox" Width="75px" OnTextChanged="TBXinsertDate_TextChanged" 
                 onfocus="Focus(this.id, this.value)"
                 onblur="Blur(this.id, this.value)" >
         </asp:TextBox>

         <cc1:TextBoxWatermarkExtender ID="insertDate_TextBoxWatermarkExtender" runat="server" TargetControlID="TBXinsertDate" WatermarkText="insert date" WatermarkCssClass="WaterMarkedTextBox">
                </cc1:TextBoxWatermarkExtender>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alter the hue of a component upon being clicked

Seeking help to modify the color of my menu elements upon clicking on the "center" or "right" containers (reverting back when clicked again). Currently, the three lines in my menu are white, but I desire them to turn red when either of these containers is ...

Substitution of "with" operator in strict mode

Let's say I have a user-entered string value stored in the variable f. For example: f = "1/log(x)"; In vanilla JavaScript, I used the following operator: f = "with (Math) {" + f + "}"; While this code worked perfectly fine in vanilla javascript, i ...

Exclusive Modal Pop-Up for First-Time Visitors - Utilizing Bootstrap, PHP, and JavaScript

Seeking assistance from the community as I have exhausted my online research efforts. I am currently working on implementing a welcome bootstrap modal in a php environment. Despite being new to php and js, I have managed to make it pop up only once using ...

When modifying a string in React, the edit always somehow ends up at the very tail end

In my ReactJS app, I have a Material-UI input element. Everything is working well except for one issue - when I try to edit the text in the middle of the string, the cursor always jumps to the end of the string after every letter I input. I suspect this m ...

Changing Enum Value to Text

In my enum file, I have defined an object for PaymentTypes: export enum PaymentTypes { Invoice = 1, CreditCard = 2, PrePayment = 3, } When I fetch data as an array from the database, it also includes PaymentType represented as numbers: order: ...

Sorting Vue.js properties based on object keys

Currently, I am dealing with a complex object that contains multiple network interfaces. Each interface is represented by a key-value pair in the object: https://i.stack.imgur.com/klkhH.png My goal is to create a Vue.js computed property that filters thi ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

Ways to assign a value to an input element in AngularJS without impacting its ngModel

JAVASCRIPT: .directive('search', [function () { return { restrict: 'A', link: function (scope, element, attrs) { attrs.$set('placeholder', 'Word...'); console.log(attrs); ...

Finding the dynamic width of a div using JavaScript

I have two divs named demo1 and demo2. I want the width of demo2 to automatically adjust when I drag demo1 left to right or right to left. <div class="wrapper"> <div class="demo"></div> <div class="demo2"&g ...

What is the best method in Selenium IDE for tracking an element based on its value?

While testing a website with Selenium IDE, I encountered an issue with the way elements are identified. The site utilizes something called "wickets" that change the ID of elements randomly, making it difficult for Selenium to record actions on certain elem ...

The method you are trying to call is not defined in Laravel

I recently developed a basic CRUD blog application with tags functionality. I have integrated tags into my pages and implemented the use of Select JS for selecting and editing tags in input fields. Now, my goal is to have the input field pre-populated wit ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Dynamically uploading an HTML file using AJAX

My webpage has a feature that dynamically creates HTML with drop down elements. Additionally, there is a "create File" button on the page. The goal is for this button to trigger an AJAX POST request and upload the dynamic page created with drag and drops a ...

Adjust the visibility of components depending on the width of the screen

In my project, I have a Wrapper component that houses filters. This component becomes visible when the openMobileFilters() function is called and disappears when closeMobileFilters() is triggered. The Wrapper component occupies the entire page, and I want ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

Storing JavaScript arrays in CSV format on the server

I am currently facing an issue while trying to save a multidimensional Javascript array as a CSV file on the server. Despite my efforts, the CSV file created does not seem to contain the actual array data, and I am unsure of what is causing this discrepanc ...

React Ant Design: Encountered a warning for 2 elements having non-unique properties

I have incorporated the Carousel component, with each one containing a different component. One contains a form, while the other includes an external library component called react-input-otp. https://codesandbox.io/s/pensive-einstein-uucvm?fontsize=14& ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

Is it necessary to include specific versions in package.json when committing the yarn.lock file?

Do you believe it is beneficial to always commit the yarn.lock file, even though all versions are clearly specified in package.json and there should be no discrepancies among team members? I personally find it to be a time-consuming practice, especially w ...