2013-01-02 2 views
-1

나는 이름, 성 및 concat 3 필드가있어.자바 스크립트로 입력 문자열 연결 방법?

내가해야 할 일은 필드 이름의 첫 번째 문자와 성을 연결하는 것입니다. 내가 쓰는 것처럼 콩크리트의 필드가 바뀌고 있습니다.

<p>Name</p><input type="text" id="name" onChange="document.getElementById('concat').value=this[0].value;" /> 
<p>Last name</p><input type="text" id="last_name" document.getElementById('txt').value=document.getElementById('txt').value + this.value;"/> 
<p>Concat</p> 
<input type="text" id="concat" /> 

그러나 첫 번째 문자는 작동하지 않는 것, 내가 문제가이 [0] .value에있을 수 있습니다 생각;

나는 지금이가 또는 첫 번째 chatacter를 얻는 방법은 다른 함수가 있습니까?

감사합니다.

+0

귀하의 자바 스크립트는 어떤 모습입니까? –

+0

위의 코드에서 html 입력 태그 안에 있습니다 : onChange = "document.getElementById ('concat'). value = this [0] .value;" – user1822263

+1

그다지 좋은 패턴이 아닙니다. –

답변

0

당신은 당신의 최초 이름 텍스트 상자에 this[0]를 사용하고 있지만, 대신 실제 값에 있어야합니다 : 당신이 명시 될 수있다, 또는

onChange="document.getElementById('concat').value=this.value[0];" 

및 첫 번째 문자를 얻을 .substring()를 사용 :

onChange="document.getElementById('concat').value=this.value.substring(0, 1);" 

입력의 첫 번째 문자가 표시됩니다. 쓰기/읽기가 약간 더 길지만 정확한 목적을 전달합니다.

참고 : 입력이 비어 경우 잘, 더 [0] 없다, 당신이 this.value[0]를 사용할 때, 당신은 당신의 concat 텍스트 상자에 삽입 된 undefined 값을 얻을 것이다. .substring(0, 1)을 사용하면 해당 텍스트가 제공되지 않습니다 (우려 사항이있는 경우).

는 또한, 마지막-이름에 대한 두 번째 텍스트 상자가 그것의 ID txt 대신 concat를 사용 onchange= 속성을 포함하지 않는 (샘플 코드 기준)이 오타에 있습니다. 또한 이름 텍스트 상자의 하위 문자열을 가져 오려고 시도하지 않습니다.

는 다음에 코드의 전체 블록을 업데이트하십시오 :

<p>Name</p> 
<input type="text" id="name" onchange="document.getElementById('concat').value=this.value.substring(0, 1);" /> 
<p>Last name</p> 
<input type="text" id="last_name" onchange="document.getElementById('concat').value=document.getElementById('name').value.substring(0, 1) + this.value;"/> 
<p>Concat</p> 
<input type="text" id="concat" /> 
0
this[0].value 

은 입력의 첫 번째 문자가 값을 필드 원한다면, 그건 당신이해야 할 일이 아니다.

this은 입력란입니다. this.value은의 첫 번째 문자로 사용할 문자열입니다. 그리고 this.value[0] 그 문자열 첫 문자를 얻을 것이다.

그래서 :

this.value[0] 
0

는 현재 수정 된 코드

<p>Name</p><input type="text" id="name" onChange="document.getElementById('concat').value=this.value[0];" /> 
<p>Last name</p><input type="text" id="last_name" onChange="document.getElementById('concat').value=document.getElementById('name').value[0] + ' ' + this.value;"/> 
<p>Concat</p> 
<input type="text" id="concat" />​​​​​​​​​​​​​​​​​​​​​​ 

자신의 코드와 비교하십시오이야, 몇 가지 실수를!

+0

첫 번째 문자가 사용되었습니다. – bukart

관련 문제