แก้ปัญหา event onchange ของ input type file ไม่ทำงานทันทีใน ใน IE
เขียนเมื่อ 12 ปีก่อน โดย Ninenik Narkdeeonchange input type file ie
คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ onchange input type file ie
ไปที่
Copy
event onchange ของ input type file ใน IE เมื่อมีการเลือกไฟล์ที่ต้องการอัพโหลด จะไม่ทำงาน
ทันที ต้องคลิกที่ว่างหรือ focus ออกจาก input type file ก่อน คำสั่งใน event onchange จึงจะทำงาน
แต่กับ บราวเซอร์อื่นๆ จะไม่เจอปัญหานี้
วิธีการในการแก้ไขคือ ให้ แทรก attribute ชื่อ onpropertychange เข้าไปใน input type file ที่ต้องการ
ให้ทำงานทันทีเมื่อคลิกเลือกไฟล์
onpropertychange="if(window.event.propertyName=='value'){$(this).blur();};"
ตัวอย่าง
<input type="file" name="pic_upload2" class="css_pic_upload2" id="pic_upload2" />
เมื่อแทรกแล้ว จะได้เป็น
<input type="file" name="pic_upload2" class="css_pic_upload2" id="pic_upload2" onpropertychange="if(window.event.propertyName=='value'){$(this).blur();};" />
ตัวอย่างทดสอบ (ให้ทำการทดสอบรันใน IE จึงจะสามารถเข้าใจผลลัพธ์ได้)
ให้ทดสอบโดลการเลือก ไฟล์ใน input type file ตัวที่สองก่อน โดยหลังจากเลือกไฟล์ จะพบว่ามีการ
alert ค่าทันที เนื่องจากเราใช้วิธีการแก้ปัญหาตามคำแนะนำข้างต้น
จากนั้น ให้ลองเลือกไฟล์ ใน input type file ตัวแรก โดยหลังเลือกไฟล์ และไม่ได้คลิกที่ว่าง หรือที่อื่นใด
คำสั่ง alert จะไม่ทำงาน จนกระทั้งเรา คลิกที่ว่าง หรือที่อื่นใด คำสั่ง alert จึงจะทำงาน
ตัวอย่างโค้ดทดสอบทั้งหมด
<!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></title> </head> <body> <!-- onpropertychange="if(window.event.propertyName=='value'){$(this).blur();};" --> <div style="margin:auto;width:800px;"> <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> <input type="file" name="pic_upload" class="css_pic_upload" id="pic_upload" /> <br /> <br /> <input type="file" name="pic_upload2" class="css_pic_upload2" id="pic_upload2" onpropertychange="if(window.event.propertyName=='value'){$(this).blur();};" /> </form> <hr /> </div> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(function(){ $(".css_pic_upload").live("change",function(){ var file_value=$(this).val(); alert(file_value); }); $(".css_pic_upload2").live("change",function(){ var file_value=$(this).val(); alert(file_value); }); }); </script> </body> </html>
กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ

URL สำหรับอ้างอิง
Top
Copy
ขอบคุณทุกการสนับสนุน
![]()