Select change 이벤트 - Select change ibenteu

jQuery selectbox change event(이벤트), select, value, text, size 제어

Select change 이벤트 - Select change ibenteu
Web Program / IT
Select change 이벤트 - Select change ibenteu
 

2015. 2. 11. 0:22

Select change 이벤트 - Select change ibenteu
https://blog.naver.com/chsmanager/220269409239

Select change 이벤트 - Select change ibenteu

jQuery 란 모든 개체를 일관되고 다루기 쉽게 해주는 자바스크립트 라이브러리로

CSS 기반의 DOM 요소 선택기능(Selector)이 뛰어나며 이벤트, Ajax 등 많은 부분을 단순화 시켜 많은 인기가 있습니다.

이번 글에는 jQuey select box 개체에 대해 다루도록 하겠습니다.

Select change 이벤트 - Select change ibenteu

기본적인 selectbox 형태인데요.

내부 숨겨진 code인 value 와 display되는 text 값을 한쌍으로 표현합니다.

1. change event(이벤트)

Select change 이벤트 - Select change ibenteu

1번 형식이나 2번 형식으로 event를 생성할 수 있습니다.

이벤트 안에 있는 this 의 경우 현재 대상이 되는 selectbox 그 자체로

this.value 하면 해당 객체의 code를 가져올 수 있습니다.

2. 선택된(selected) value 가져오기

Select change 이벤트 - Select change ibenteu

$("#아이디 option:selected").val();

1번같이 본인 객체의 경우 this로 가져올 수 있지만

다른 객체 안에서 부른다면 위와 같은 형식으로 코드값을 가져올 수 있습니다.

다른 표현으로 $("#아이디 option:selected").attr("value"); 로도 가능합니다.

3. 선택된(selected) text 가져오기

Select change 이벤트 - Select change ibenteu

$("#iptFruit option:selected").text();

jQuery select box 의 선택된 텍스트를 가져오기 위해서는 위와 같이 text() 라고 속성을 사용하시면 됩니다.

4. 셀렉트박스안의 아이템 갯수 구하기

Select change 이벤트 - Select change ibenteu

size 혹은 length 프로퍼티로 아이템 갯수를 구할 수 있습니다.

그리고 선택한 값 이전, 이후에 있는 아이템 갯수도 prevAll, nextAll 로 가능합니다.

단 선택한 아이템은 제외됩니다.

5. 선택된 아이템 index 가져오기, 선택하기

Select change 이벤트 - Select change ibenteu

셀렉트 박스에서 선택한 아이템의 위치를 가져올 수 있습니다. 위치(index)는 0부터 시작합니다.

그리고 선택하는 위치를 지정하는 것도 다양한 방법을 제공하니

원하는 방법으로 처리하면 되겠죠.

6. 아이템 삭제하기

Select change 이벤트 - Select change ibenteu

jquery 를 이용하면 어떤 위치에 있던간에 쉽게 아이템을 삭제할 수 있습니다.

원하는 value 값의 경우 index를 구한 후 remove 함수를 이용해서 삭제하면 됩니다.

처음과 끝의 경우는 first, last 예약어로 더 직관적으로 처리가 가능합니다.

7. 아이템 추가하기

Select change 이벤트 - Select change ibenteu

아이템 추가의 경우도 어떤 자리에 추가할 수 있는 다양한 방법을 제공합니다.

또한 추가된 아이템의 경우 셀렉트박스의 아이템으로 인정받아 새로운 index 로 실시간 적용됩니다.

이상으로 다양한 jQuery select box 제어 하는 방법에 대해 알아봤는데요.

jQuery 의 경우 css 에 근거다양한 객체에 비슷한 이벤트, 프로퍼티를 제공하므로

한두개의 객체만 사용한다면 익숙해 질수 있을거라 생각됩니다.

The change event is fired for <input>, <select>, and <textarea> elements when the user modifies the element's value. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

  • When a <input type="checkbox"> element is checked or unchecked (by clicking or using the keyboard);
  • When a <input type="radio"> element is checked (but not when unchecked);
  • When the user commits the change explicitly (e.g., by selecting a value from a <select>'s dropdown with a mouse click, by selecting a date from a date picker for <input type="date">, by selecting a file in the file picker for <input type="file">, etc.);
  • When the element loses focus after its value was changed: for elements where the user's interaction is typing rather than selection, such as a <textarea> or the text, search, url, tel, email, or password types of the <input> element.

The HTML specification lists the <input> types that should fire the change event.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

addEventListener('change', (event) => {});

onchange = (event) => { };

Event type

Examples

<select> element

HTML

<label>
  Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>

<div class="result"></div>

body {
  display: grid;
  grid-template-areas: "select result";
}

select {
  grid-area: select;
}

.result {
  grid-area: result;
}

JavaScript

const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});

Result

Text input element

For some elements, including <input type="text">, the change event doesn't fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event.

HTML

<input placeholder="Enter some text" name="name" />
<p id="log"></p>

JavaScript

const input = document.querySelector('input');
const log = document.getElementById('log');

input.addEventListener('change', updateValue);

function updateValue(e) {
  log.textContent = e.target.value;
}

Result

Specifications

Specification
HTML Standard
# event-change
HTML Standard
# handler-onchange

Browser compatibility

BCD tables only load in the browser

Different browsers do not always agree whether a change event should be fired for certain types of interaction. For example, keyboard navigation in <select> elements used to never fire a change event in Gecko until the user hit Enter or switched the focus away from the <select> (see bug 126379). Since Firefox 63 (Quantum), this behavior is consistent between all major browsers, however.