When a user inputs text into a textbox and clicks a link button, it works in Firefox but

There is a textbox on my form with a linkbutton positioned next to it. The ID of the textbox is textbox1 and the linkbutton is lbSearch.

In the page_load event, I include the following code:

this.TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode)
        {
            if ((event.which == 13) || (event.keyCode == 13))                              
            {
                document.getElementById('" + this.lbSearch.ClientID + "').click();
                return false;
            }
        }
        else 
        {
            return true
        }; ");

This code works in Firefox but not in Internet Explorer due to how the linkbutton is rendered as an anchor tag.

The linkbutton is rendered like this:

<a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$zoeken1$lbSearch", "", true, "search", "", false, true))' id="ctl00_zoeken1_lbSearch">zoek</a>

I attempted a solution with the following code snippet:

function onkeydown does not always return a value
rule: 1, column: 243

source:


if(event.which || event.keyCode)
{
if ((event.which == 13) || (event.keyCode == 13)) 
{ 
    var link = document.getElementById('ctl00_zoeken1_lbSearch'); 
    __doPostBack(link.id.replace('_','$'),''); 
    return false;
}
else
{
    return true;
}
} 
else
{
return true;
}; 

Is there a way to resolve this issue without converting the linkbutton into an imagebutton or regular button?

Answer №1

Anchor tags in IE may not trigger the click event due to the absence of an onclick method in the rendered HTML tag.

<a href="javascript:__doPostBack('somename','')">text here</a>

Below are some solutions:

var link = document.getElementById('');

__doPostBack(link.id.replace('_','$'),'');

or

eval('(' + link.href + ')');

EDIT:

I have tested this on various browsers like IE, FF, Chrome, and Safari:

<a href="javascript:alert('test');" id="ctl00_zoeken1_lbSearch">zoek</a>
<input type="text" onkeydown="KD(event)" />
<script>
    function KD(e){
        e = e || window.event
        var k = e.keyCode || e.which;
        if(k==13){
            var a = document.getElementById('ctl00_zoeken1_lbSearch');
            //eval(a.href.replace(/javascript:/g,'')); //if this doesn't work use doPostBack
            __doPostBack(a.id.replace('_','$'),''); 
        }
        return false;
    }    
</script>

Hopefully, this solution will work for you now!

Answer №2

It is recommended to use the keypress event instead of keydown for detecting the enter key. It's also best practice to utilize a function rather than embedding long pieces of code in attributes. Additionally, if you wish to prevent the default action, you should return false within the onkeypress attribute as shown below.

<script type="text/javascript">

function checkEnterPressed(evt, linkButtonId) {
    var charCode = evt.keyCode || evt.which;
    if (charCode == 13) {
        // Perform actions specific to LinkButton here...
        return false;
    }
    return true;
}

</script>


this.TextBox1.Attributes.Add("onkeydown",
    "return checkEnterPressed(event, '" + this.lbSearch.ClientID + "')");

Attempting to manipulate IDs for passing values to __doPostBack appears unreliable and gimmicky. It would be advisable to explore alternative methods. Is there a way to retrieve the value ctl00$zoeken1$lbSearch from the this.lbSearch LinkButton object through another approach?

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

In a JavaScript project, encountering an error when using FB.logout that states "The expression is undefined and not a function."

Seeking to integrate Login with FB into my react website. FB.init({ appId : app_id, cookie : true, xfbml : true, version : 'v5.0' }); Followed by FB.getLoginStatus(({status}) => { if (status === 'conn ...

What are the steps for making Ajax calls?

I have been working on a Wikipedia viewer for my freecodecamp project. However, I am facing issues with the AJAX request as it keeps failing every time without returning any results. var url, value; $(document).ready(function() { $("button").on("click ...

React failing to detect updated state from input fields during initial rendering

Hey there, fellow developers! I'm currently working on a simple client in React to test out some functionalities of my API. While my Node.js knowledge is extensive, my understanding of React, states, and hooks is still a work in progress. The Issue: ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

What is the best way to input information into my Google spreadsheet with React JS?

After using https://github.com/ruucm/react-google-sheets as a reference, I encountered a persistent gapi 404 error whenever I tried to run the code. It seems like the GitHub link might not exist, causing my app to fail. However, I could be mistaken. Is t ...

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

What is the best way to temporarily stop a jQuery `.each()` loop until user input is received?

I'm facing an issue with my jQuery, where the .each loop doesn't pause for user input before continuing the iteration. Here's a snippet of my code along with what I expect to happen: <html xmlns="http://www.w3.org/1999/xhtml"> <he ...

Using Three JS: Import an OBJ file, move it to the center of the scene, and rotate around it

I am trying to figure out how to load an OBJ file and translate its coordinates to the world origin (0,0,0) in order to make orbit controls function smoothly without using Pivot points. My goal is to automatically translate random OBJ objects with differe ...

Ways to have a React Component trigger a function with each state update

Using this specific component, the getDisplay function is triggered on every update like normal. When the <div> element is clicked, it becomes hidden: class Example extends React.Component { constructor(props) { super(props); thi ...

Unable to execute JavaScript on Node.js

I recently installed Node.js so I could run some JavaScript codes on LeetCode, but unfortunately, I encountered an issue. I then tried installing the Code Runner extension on VS Code to see if that would help, but this is the output I received: [Running] n ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

Tips for transforming a JSON object (originated from jquery-css-parser) into properly formatted CSS code

Currently, we are utilizing a jQuery plugin in our project to convert CSS to a JSON object. The plugin can be found at the following link: Now, we have a requirement to convert the JSON object back to CSS in string format. Unfortunately, the plugin we ar ...

Is there a way to activate the window load event within this Jest test scenario?

I'm in the process of setting up my first Jest test for DOM manipulation and jQuery in my Rails project. Right now, I'm facing a basic challenge of ensuring that imported JavaScript functions are functioning as expected. In order to tackle this ...

Tips for resolving a node.js error when you encounter a "GET / error" message

I followed a tutorial and added the code below: var express = require('express'); // Web Framework var app = express(); var sql = require('mssql'); // MS Sql Server client // Connection string parameters. var sqlConfig = { user: & ...

The security flaw in RedirectMode in ASP.NET

Scott Guthrie discusses the ASP.NET Security vulnerability in his blog post linked here, recommending that for ASP.NET 3.5 SP1 and above, the custom errors section should have the following attribute set: redirectMode="ResponseRewrite" What is the signif ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...

What is the best way to loop through strings in a request object?

I am currently working with Express and need to scan the POST requests to create an array called openingTimes. After that, I want to generate a MongoDB document based on the user inputs. The code snippet below is functional, but I am looking for a way to ...

Utilizing async/await as a module function: A comprehensive guide

Express Route: const express=require('express'); const router=express.Router(); const trackRepo=require('../model/track'); router.post('/live',function(req,res){ const time=1439832167; const list=trackRepo.getAlerts ...

Issue with AJAX callback function closing too quickly

I am having an issue with a function in my ajax callback that displays a div with a Bootstrap alert inside. The problem is that it only stays visible for about half a second before disappearing. I would like it to remain visible for 2 seconds. I have set a ...