how to make html page detect enter key pressed? - javascript

I am using VSTS 2008 + C# + .Net 3.5 + IIS 7.0 + ASP.Net to develop a web application. The web application has an aspx page called default.aspx. And I want to implement the effect that when user press the enter key of keyboard, it is the same effect of press button "Action". Any ideas how to implement?
Here is the default.aspx file,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript">
function requery() {
var query = location.search.substring(1);
var pairs = query.split("&");
var param1Value = document.getElementById("txtParam1").value;
url = "/Default.aspx?param1=" + param1Value;
for (var i = 0; i < pairs.length; ++i) {
var pair = pairs[i];
if ((pair.indexOf("param1") != 0) && (pair.length > 0)) {
url += "&" + pair;
}
}
location.href = url;
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtParam1" runat="server"></asp:TextBox>
<input type="button" value="Action" onclick="requery()" />
</div>
</form>
</body>
</html>
Here is the code behind file default.aspx.cs,
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtParam1.Text = Request.QueryString["param1"];
}
}
}

add an event handler to the document's keydown event. explanation in the comments.
function keydownHandler(e) {
if (e.keyCode == 13) { // 13 is the enter key
requery(); // call your function.
// alternately, give your button an id and used
// document.getElementById('myID').click();
// prevent the browser from doing whatever it normally
// does when you push the enter key.
// (not tested for this situation, may need tweaking)
if (e.preventDefault) {
e.preventDefault(); // FF,chrome
}
else {
return false; // IE
}
}
}
// register your handler method for the keydown event
if (document.addEventListener) {
document.addEventListener('keydown', keydownHandler, false);
}
else if (document.attachEvent) {
document.attachEvent('onkeydown', keydownHandler);
}

If you are browsing from Internet Explorer this is an annoying issue. Add a textbox with a style of display:none;visibility:hidden; The enter key will respond appropriately. This typically occurs on forms with one text input in IE. Add the hidden one as mentioned above under your first input field

Related

How do I print the result of a search() method in JavaScript?

I posted a question earlier regarding a school problem I was working on. I have what I believe to be the correct function per the assignment, but I am stuck. I need to have the alert() in my code display the index position of the substring it is searching for. Everything else works but I don't know how to send that info back to a variable that I can print to the screen. My code is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lesson 6 Application Project A</title>
<script language="JavaScript" type=text/javascript>
<!--
/*****************************************************************************
The placeholders sub and string are used to pass as arguments the
user's entry into the text box and the textarea. The variable where
is assigned the result of a method which returns the index (integer)
of the first occurence of sub (the string the program is searching for).
Start the search at the beginning of string (the text that is being searched).
Since the string is zero based, add 1 is to get the correct position of sub.
*****************************************************************************/
function search(sub, string) {
var where;
if (string.search(sub) != -1){
where = alert("Your index position is: " + where);
}
else{
where = alert("Could not find your string!");
}
}
//-->
</script>
</head>
<body>
<h3>CIW JavaScript Specialist</h3>
<hr />
<form name="myForm">
<p>
<strong>Look for:</strong>
<input type="text" name="what" size="20" />
</p>
<p>
<strong>in this string:</strong>
<textarea name="toSearch" rows="4" cols="30" wrap="virtual">
</textarea>
</p>
<p>
<input type="button" value="Search"
onclick="search(myForm.what.value, myForm.toSearch.value);" />
</p>
</form>
</body>
</html>
Try this
function search(sub, string) {
var where = string.indexOf(sub);
if (where != -1){
alert("Your index position is: " + where);
}
else{
alert("Could not find your string!");
}
}
Your where variable should be assinged to the result of the search.
function search(sub, string) {
var where = string.search(sub);
if (where != -1){
alert("Your index position is: " + (where + 1));
}
else{
alert("Could not find your string!");
}
}
My solution to my own problem was to create a variable called position and set it to receive the index position of the substring. I could then add that into my alert() and display the results to the screen. Corrected code is as follows:
function search(sub, string) {
var where;
var position = string.search(sub);
if (string.search(sub) != -1){
where = alert("Your index position is: " + position);
}
else{
where = alert("Could not find your string!");
}
}

Javascript Executor not clicking input inside iframe - Selenium

I had a problem with Javascript executor for selenium when clicking a certain input inside an iframe. The problem happens only on chrome works fine on IE and FF, don't know why
here's the html file:
<iframe id="iframContainer" ng-src="app/docManagement/upload/iframe/iframe.html" src="app/docManagement/upload/iframe/iframe.html">
<!DOCTYPE html>
<html lang="en" dir="{{dir}}" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<script src="jquery-1.9.1.min.js" type="text/javascript">
<script src="uploader.js" type="text/javascript">
<style type="text/css">
</head>
<body class="upload-control">
<div id="drop" class="dragdrop_zone">
<input id="uploader" type="file" multiple="" name="file">
</div>
<script type="text/javascript">
</body>
</html>
</iframe>
and here's my code to click on the element using selenium executor:
int uploadArea = Driver.GetFirstFrameIndex();
Driver.Upload_File_Generic(FileUpload);
try
{
Thread.Sleep(2000);
Driver.SwitchToFrame(uploadArea);
Initiate_Driver.ClickJSElement(By.Id(AddREsources_IDs.UploadArea),"Uploader",Messages.ElementValidation.Mandatory);
}
catch
{
}
Initiate_Driver.GetOutofFrame();
public static void SwitchToFrame(int index)
{
try
{
driver.SwitchTo().Frame(index);
}
catch
{
Messages.NoSuchFrame(FrameName, validation);
}
}
public static void ClickJS(By by, string ElementName)
{
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
string _JSCommand = "";
if (by.ToString().Contains("Id"))
{
string ID = by.ToString().Replace("By.Id: ", string.Empty);
_JSCommand = "document.getElementById('" + ID + "').click();";
}
else if (by.ToString().Contains("Name"))
{
string Name = by.ToString().Replace("By.Name: ", string.Empty);
_JSCommand = "document.getElementByName('" + Name + "').click();";
}
executor.ExecuteScript(_JSCommand);
}
AGAIN : The proble happens only on chrome but it's working very fine on IE and FF.

document.getElementById('button2').click(); not working

I am try to automatically fire a sub routine with with a javascript "document.getElementById('button2').click();" as it is in the below code. Can someone please help me see why the code is not working. Thank you
<%# Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" debug = "true"%>
<%# Import Namespace="System.Data.SqlClient"%>
<%# Import Namespace="System.Data"%>
<script language="vb" runat="server">
Sub sendmsg(sender As Object, e As EventArgs)
response.Redirect("index.aspx")
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function Confirm() {
var str = $('#loutput').val(); //'We are inviting you for s special business meeting on Tueday, at No 12, Fred street. for more information please call 02341123333';
var updateString = function(input_text) {
//1. Find consecutive 11 numeric digits
var match = input_text.match(/\d{11}/);
//2. divide it into a string of 3s separated by space
var new_str = '';
for (var i = 1; i < match[0].length + 1; i++) {
new_str = new_str + match[0][i - 1];
if (i > 1 && i % 3 == 0)
new_str = new_str + ' ';
}
//3. Replace old match no. with the new one
console.log(match)
if (match[0] != '')
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
confirm_value.value = "Yes";
input_text = input_text.replace(match[0], new_str)
$('#loutput').val(input_text);
confirm2()
//document.getElementById('loutput').innerHTML = input_text;
} else {
confirm_value.value = "No";
confirm2()
}
$('#loutput').val(input_text);
//document.getElementById('loutput').innerHTML = input_text;
};
updateString(str);
};
function confirm2() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(" send the message now?")) {
confirm_value.value = "Yes";
document.getElementById('button2').click();
//document.getElementById('loutput').innerHTML = input_text;
} else {
confirm_value.value = "No";
}
//document.getElementById('loutput').innerHTML = input_text;
};
</script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<form runat="server" action="formatmessage3.aspx" method="post">
<input type="texarea" id="loutput" name="loutput" value="<%=request.form ("loutput") %>" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>
<asp:button ID="button2" OnClick="sendmsg" Text="send" runat="server" />
</form>
</body>
</html>
The problem here is the fact you are using a .NET button with runat="server" so it is going to change the id of the button to a different value.
<asp:button ID="button2" OnClick="sendmsg" Text="send" runat="server" />
You either have to reference the element by a class
document.getElementsByClassName("myClass")[0].click();
or reference the dynamic name
document.getElementById("<%= button2.ClientID %>").click();
or in .NET4 you can use ClientIDMode="Static"

IE11 bug - calling javascript getAttributeNode method brakes mergeAttributes

There is some really strange behavior in javasrcipt after recent update of IE (11.0.27) in IE=7 mode, in previous versions script below works as expected (including IE8-IE11.0.24) .
So it's caused by calling Element.getAttributeNode('class') , after this call is made on element that element will throw error (Unspecified Error) if you'll try to merge it`s attributes with another element with Element.mergeAttributes method.
Demo (happens only when devtools/console is turned off and in IE-7 mode with current IE11 version) : LINK
Question: Is there any way to avoid this, and is there any alternative methods for those mentioned above? Issue is that those two methods are heavily used by mootools and jquery selectors and my framework is based on mootools. So after I use selector which looks like $$('input[class=randomclass]') all inputs will be corupted and i`ll not be able to clone them (mergeAttributes).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<html>
<head>
<script type='text/javascript'>
window.onload = function() {
org = document.getElementById('o');
cln = document.getElementById('c');
btn1 = function() {
cln.mergeAttributes(org);
alert(cln.className)
}
btn2 = function() {
org.getAttributeNode('class');
try {
cln.mergeAttributes(org);
} catch (e) {
alert(e.description)
}
}
}
</script>
</head>
<body>
<div id='placeHolder'>
Original:
<input type='text' class='original' id='o'></input>
<br> Clone:
<input type='text' class='clone' id='c'></input>
<br>
</div>
<input type='button' value='mergeAttributes without "getAttributesNode" ' onclick='btn1()'>
<br>
<input type='button' value='mergeAttributes with "getAttributesNode" ' onclick='btn2()'>
<br>
</body>
</html>
It seems the issue is in the jQuery library. This solution was provided by cqrranthuohill3 from the dataTabes forum. He referenced Dottoro.com
In jquery.js in the cloneFixAttributes( src, dest ) function about line 6092. Replace:
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
With:
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
try{
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
} catch (exception) {
for (var i=0; i < src.attributes.length; i++) {
var attr = src.attributes[i];
var attrName = attr.name.toLowerCase ();
if (attrName != "id" && attrName != "name") {
dest.setAttribute (attr.name, attr.value);
}
}
}
Give that a go.
After some suggestion i manage to fix the problem related to Element.getAttributeNode('class') as it was broking Element.mergeAttributes(src), i had to replace all instances of Element.getAttributeNode in mootools with custom function.
Function which replaced default Element.getAttributeNode:
getAttributeNode_M = function(el, attr) {
var AllAttribues = el.attributes;
for (var i = 0; i < AllAttribues.length; i++) {
if (el.attributes[i].name.toLowerCase() == attr.toLowerCase()) {
return el.attributes[i];
}
}
return false;
}

Smallest code possible to filter checkboxlist through javascript

Project doesn't need any javascript libraries such as jQuery, Dojo, Prototype so there is no easy way i suppose. I would like to have in-depth answers for the question explaining how would one do this. As most of you might know asp.net checkboxlist emits a markup like below in Flow repeatLayout.
<span>
<checkbox><label></br>
<checkbox><label></br>
<checkbox><label></br>
</span>
i haven't put the ending/closing tags for simplicity. We have a textbox for searching through this list of checkbox.Now comes the question,
How would i Filter the checkboxlist when user types the search term in the textbox and hide the unmatched checkbox+label.
some more questions i would like getting answers for that are related to above
Is there any ready made STANDALONE script for this purpose?
Is there a pattern , article, post explaining the glitches, points to remember while providing search functionality? something like onkeydown don't do this,
My Idea right now would be have a cached collection of label tags innerHTML then loop through each tag and check for search term, when found hide all others but show only matching.[My Concern is what will happen when list is too long, on every keypress looping is not the best idea i suppose]
Your suggestions, answers, solution, scripts are welcome
This solution is based on Ktash's answer. I made it cause I want to learn more about javascript, DOM navigating and RegExp.
I changed "keypress" event with "keydown" since the previous doesn't trigger on backspace/delete so deleting all the characters with backspace/delete still left the list filtered.
[Default.aspx]
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RealtimeCheckBoxListFiltering.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function () {
var tmr = false;
var labels = document.getElementById('cblItem').getElementsByTagName('label');
var func = function () {
if (tmr)
clearTimeout(tmr);
tmr = setTimeout(function () {
var regx = new RegExp(document.getElementById('inputSearch').value);
for (var i = 0, size = labels.length; i < size; i++)
if (document.getElementById('inputSearch').value.length > 0) {
if (labels[i].textContent.match(regx)) setItemVisibility(i, true);
else setItemVisibility(i, false);
}
else
setItemVisibility(i, true);
}, 500);
function setItemVisibility(position, visible)
{
if (visible)
{
labels[position].style.display = '';
labels[position].previousSibling.style.display = '';
if (labels[position].nextSibling != null)
labels[position].nextSibling.style.display = '';
}
else
{
labels[position].style.display = 'none';
labels[position].previousSibling.style.display = 'none';
if (labels[position].nextSibling != null)
labels[position].nextSibling.style.display = 'none';
}
}
}
if (document.attachEvent) document.getElementById('inputSearch').attachEvent('onkeypress', func); // IE compatibility
else document.getElementById('inputSearch').addEventListener('keydown', func, false); // other browsers
};
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:TextBox runat="server" ID="inputSearch" ClientIDMode="Static" />
</td>
</tr>
<tr>
<td>
<asp:CheckBoxList runat="server" ID="cblItem" ClientIDMode="Static" RepeatLayout="Flow" />
</td>
</tr>
</table>
</form>
</body>
</html>
[Default.aspx.cs]
using System;
using System.Collections.Generic;
namespace RealtimeCheckBoxListFiltering
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
cblItem.DataSource = new List<string>() { "qwe", "asd", "zxc", "qaz", "wsx", "edc", "qsc", "esz" };
cblItem.DataBind();
}
}
}
var tmr = false;
var labels = document.getElementsByTagName('label')
var func = function() {
if (tmr) clearTimeout(tmr);
tmr = setTimeout(function () {
var regx = new Regex(inputVal); /* Input value here */
for(var i = 0, size = labels.length; i < size; i++) {
if(regx.match(labels[i].textContent || labels[i].innerText)) labels[i].style.display = 'block';
else labels[i].style.display = 'none';
}
}, 100);
}
if (document.attachEvent) inputField.attachEvent('onkeypress', func);
else inputField.addEventListener('keypress', func, false);
Not perfect, and not all the way complete, but it should get you started on it. There is a 100 millisecond delay before it performs the loop so that it won't run on every keypress, but likely just after they've stopped typing. Probably want to play with the value a bit as you see fit, but it gives you the general idea. Also, I didn't set the variables for inputField nor inputVal, but those I assume you would already know how to grab. If your labels are not a static list onload, you'll probably want to get the list every time.

Categories

Resources