WEB

html table 상태에서 태그 <td> <tr> 호 형성된 테이블에서 enter 값 이벤트 받기 관련

AlrepondTech 2020. 9. 21. 02:04
반응형

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

출처: http://stackoverflow.com/questions/11958021/focus-on-an-anchor-tag

I have some HTML that looks something like this:

<div id="zoomed" style="display:none; position:absolute;">
            <a href="#" alt="close" id="closeLink" onclick="closeZoom();" tabindex="2"><img alt="close" style="border-style:none" class="close" id="closeButton" src="Images/trans.png"/></a>
            <div class="zoomParent">
            <table>
                <tbody data-bind="with: currentFactor">
                    <tr><td class="zIngHeader" colspan="3">
                    <span data-bind="text: FactorName"></span>
                    </td>
                    </tr>
                    <tr>
                        <td class="zMin" data-bind="text: formatValues(Min)"></td>
                        <td><input type="text" data-bind="value: currentValue" class="channel" onkeydown="EnterToTabHack(event);" tabindex="1"/></td>
                        <td class="zMax" data-bind="text: formatValues(Max)"></td>
                    </tr>
                    <tr><td colspan="3" class="graphCell" data-bind="animateColor: $root.statusColor"><div id="zoomPlot" class="zoomPlotStyle"></div></td></tr>
                </tbody>
            </table>
            </div>
        </div>

Now, when you are in the text box and you hit the tab key, the anchor tags gets focus, so if you immediately hit enter, you'll run the function closeZoom(). This works fine.

What I want to do is have so if you are in the textbox and you hit enter, it will behave the same way as if you hit tab. So I have a function to do this:

 function EnterToTabHack(event) {
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
            $(".channel").blur();
            $("#closeLink").focus();
        }
    }

The blur part works fine, the value in the textbox gets written back to my viewmodel as I wanted, but the focus doesn't end up on my link. Hitting enter twice should accept the value in the textbox (which is does) and then close the window (it doesn't).

Any idea what might be wrong here? I see no error messages, but clearly the focus isn't on the anchor link like it would be if I hit tab (note: just blurring doesn't seem to do it either).

Edit: I've added a little more of the html because it may, or may not, be relevant. In particular, I'm using KnockoutJS for data binding and I think that is making it impossible to use the type of jQuery bindings (of events) that several people have suggested, or at least, if I were to use them, I'd have to rebind then every time "currentFactor" changed because I think what knockout is doing is destroying everything in the body of the table and recreating it when that part changes.

Another Edit: First, a really big thanks to everybody who has tried to help so far! I really appreciate you taking the time to take a look at this.

I played around and put together a JS Fiddle:

http://jsfiddle.net/sUh8G/4/

At first I was confused because, of course, it worked fine! Then I added the styles for the img and it seems that using sprites this way is what breaks it. If you remove all the img styles from the css, it works fine. With them, I can't focus it programmatically.

Anybody seen anything like that before?

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

ok here is a simplified fiddle, I used the js code from one of the other answers. The focus seems to work on my current browser FF 14

http://jsfiddle.net/ZKYc3/

Here is a version that works in FF 14

http://jsfiddle.net/ZKYc3/2/ this one has a alert when the closelInk is clicked. Double enter triggers the alert. Perhaps all you need to do is take the event handling out of the html and leave it up to jquery to take care of

Update: see http://knockoutjs.com/documentation/event-binding.html

I think you should probably follow that since you are using knockout

Updated fiddle working

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Your fiddle works, but it's using jQuery to wire up the keypress event. This doesn't seem to work with knockoutjs when I use a with clause (it seems reevaluating the with clause removes all the jQuery wired events).– Matt Burland Aug 14 '12 at 18:36
your original code works if you add an alt tag to the image (in fiddle at least) except it works right away as soon as you hit enter once – Huangism Aug 14 '12 at 20:27
@MattBurland the only way I have made it work is changing the original onkeydown to onkeyup for the input tag. Anything else would trigger the click event 1 click too early or not at all. This is without binding the events using jquery to avoid conflict – Huangism Aug 14 '12 at 21:00
@MattBurland see my update, I think we been doing the wrong approach – Huangism Aug 14 '12 at 21:11
I'd tried event binding with knockout before and I have the same problem. I don't think the problem is getting the event to fire (either event binding with KO, onkeydown/up/press or jQuery binding done when the current item changes all fire). The problem is that the focus doesn't want to go to my anchor tag for some reason

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

function EnterToTabHack(event) {
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
            $(".channel").blur();
        }
    }    

$(".channel").blur(function() {
      $("#closeLink").focus();
    });

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

I would take the onclick and onkeydown out of your html elements...

<a href="#" id="closeLink" tabindex="2"><img class="close" style="border-style:none" id="closeButton" src="Images/trans.png"/></a>

<input type="text" data-bind="value: currentValue" class="channel" tabindex="1"/>

and use jquery to wire up these events...

$(function(){
    $('#closeLink').click(closeZoom);

    $('.channel').keypress(function(e){
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) { //Enter keycode
           $(".channel").blur();
           $("#closeLink").focus();
        }
    });
});

I used keypress here instead of keydown, because keydown will focus the link, and then keyup will fire the click event. If this is the behavior you want, use keydown. Otherwise, keypress will set the focus to the link, and the second enter press will fire the click event.

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

use the keyup event

<a href="#" id="closeLink" onclick="closeZoom();" tabindex="2" ><img alt='testtesttest' class="close" style="border-style:none" id="closeButton" src="Images/trans.png"/></a>

<input type="text" data-bind="value: currentValue" class="channel" onkeyup="EnterToTabHack(event);" tabindex="1"/>

then the js

function EnterToTabHack(event) {   
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {        
            $("#closeLink").focus();
        }
}

http://jsfiddle.net/wirey00/KcRyV/

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://blog.naver.com/amnesty7?Redirect=Log&logNo=30039798083

<script language="JavaScript">
<!--
function enter01()
{
document.form01.action="aaa.htm";
document.form01.submit();
}
-->
</script>

<form name=form01>
<table>
  <tr>
    <td>ID</td>
    <td><input type=text name=txt01 size=20 value="" ></td>
  <tr>
  <tr>
    <td>PW</td>
    <td><input type=text name=txt02 size=20 value="" onkeydown="javascript: if (event.keyCode == 13) {enter01();}"></td>
  <tr>
</table>
<form>

[출처] Enter 치면 Submit 수행|작성자 까만머루

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://cafe.naver.com/lpinfotech/137

후우...

책을 산지 1주일이 되어가는데 그동안 바쁜 업무로 사놓고 보지도 못하고 이제서야 짬내서 조금 씩 보는데 처음부터 힘들게 하네.

 

기본적으로 화면에서 입력 받은 데이터를 비동기식으로 처리를 하여 결과를 보여주는 첫 예제를 이해하는데 시간이 좀 걸렸다. 근데 해보고 나니 별거 아니라는 생각이 든다는 ㅋ 처음부터 너무 자만해졌나.

====================================================

index.html

===================================================

<html>

<head>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script language="javascript" src="/TestAjax/common/ajax.js"></script>

    <title>Ajax On Java, Chapter 2 Example</title>

</head>

<body onload="focusIn();">

    <h1>Ajax Character Decoder</h1>

    <h2> Press a key to find its value.</h2>

    <table>

        <tr>

            <td>

                Enter key Here ->

                <input type="text" id="key" name="key" onkeyup="convertToDecimal();">

            </td>

        </tr>

    </table>

    <br />

    <table>

        <tr>

            <td colspan="5" style="border-bottom:solid black 1px;">

                Key Pressed:

                <input type="text" readonly id="keypressed">

            </td>

        </tr>

        <tr>

            <td> Decimal </td>

        </tr>

        <tr>

            <td> <input type="text" readonly id="decimal"></td>

        </tr>

    </table>

</body>

</html>

<!--/********************************************************************************************************

우선 화면은 한개의 문자를 받는 것이고 그 결과를 출력하기 위한 id값이 decimal이라는 input태그로 구성되어 있다.

스타일시트는 뭐 설명할 필요가 없으니 생략 다음 ajax.js 파일의 스크립트 부분을 살펴보면

********************************************************************************************************/-->

====================================================

ajax.js

===================================================

var req;

function convertToDecimal() {

    var key = document.getElementById("key");

    var keypressed = document.getElementById("keypressed");

    keypressed.value = key.value;

    var url = "/TestAjax/response?key=" + escape(key.value);

    if (window.XMLHttpRequest) {

        req = new XMLHttpRequest();

    } else if (window.ActiveXObject) {

        req = new ActiveXObject("Microsoft.XMLHTTP");

    }

    req.open("Get", url, true);

    req.onreadystatechange = callback;

    req.send(null);

}

function callback() {

    alert(req.readyState);

    if (req.readyState == 4) {

        alert(req.status);

        if (req.status == 200) {

            var decimal = document.getElementById('decimal');

            decimal.value = req.responseText;

        }

    }

    clear();

}

function clear() {

    var key = document.getElementById('key');

    key.value = "";

}

function focusIn() {

    document.getElementById('key').focus();

}

<!--/********************************************************************************************************

일단 req라는 객체를 생성하는데 브라우저에 따라 틀린 놈을 가져온다. 보통 XMLHttpRequest를 가져온다. IE7버전 이하는 ActiveXObject를 가져 올것이다.

객체를 생성하고 open 함수를 통하여 get 또는 post 방식을 정하고 데이터를 처리할 java파일의 url정보를 같이 넘긴다.

req.open("get",url,true);

   true는 호출을 비동시적으로 할 것인지 동기적으로 할 것인지를 결정하는것. 이 매개변수가 true로 설정되면 요청은비동기적으로 이루어 진다.  보통 ajax 설계할때는 true값으로 고정한다.쉽게 말해 (" 이 요청 때문에 다른 작업들을 멈출 수 없다. 그러니까 응답 데이터가 오면 알려달라는것이다.")

그다음 상태가 변경될때마다 호출할 함수를 정한다.

req.onreadystatechange = callback;

callback라는 함수를 상태가 변경될때마다 호출하게 된다.

 

callback함수를 한번 보자.

req.readyState ==4

readyState의 값은 0부터 4까지 있다.

0: Uninitialized

1: Loading

2: Loaded

3: Interactive

4: Complete

이 값이 4일때가지 지속적으로 대기하다가 4가 되면 결과를 수행하게되면 된다.

그다음 확인하는것이 req.status 인데 HTTPRequest가 OK(200)라는 상태를 반환했는지 확인해야한다.

 

********************************************************************************************************/-->

 

 

 

=================================

=================================

=================================

 

 

 

 

 

반응형