[사전환경]  * jquery 설정이 되어있을것! 

코드시작!! 

 

1. file을 받는 input과 미리보기할 이미지를 코드를 작성한다.

<input type="file" id="file" class="imgs" name="mainImg">
<img src="" />

 

2. 스크립트 작성

파일을 여러개 입력하더라도 각각 미리보기를 띄울 수 있다.

<script>
	$(function() { 
		$("input[type='file']").change(function(){
		  $(this).siblings("img").attr('src', URL.createObjectURL(this.files[0]));
	    });
	})
</script>

 

 

서비스를 유지보수 하려 스크립트를 보다보면  name*=”value” 이렇게 생긴 선택자가 있다. 

 

예) 

$("input[name*=arr]").prop("checked",true); 

 

이렇게 하는 이유는 "arr" 문자열을 포함하는 값으로 지정된 속성이있는 요소를 선택하기 위해서다. 

즉 name에 "arr"이 포함된 모든 input 을 선택하게된다.

이 선택자는 아주 관대한 jQuery 속성 선택기이다. 

아래 코드와 같이 지정한 문자열을 포함하면 모두 선택해준다.. 

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>attributeContains demo</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<input name="man-news"> --> 값이 들어간다. 
<input name="milkman"> --> 값이 들어간다. 
<input name="letterman2"> --> 값이 들어간다. 
<input name="newmilk">
 
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
 
</body>
</html>

 

고로,, 

작업이 필요해 태그를 추가하거나 수정하려는 경우 같은 이름이 겹치지 않게 주의해야한다!!  

더 관대한 선택자로는 e.g. [attr~="word"] 가 있다고한다~! 

 

 

https://api.jquery.com/attribute-contains-selector/

+ Recent posts