jQuery onchange/onfocus select box to display an image?

丶灬走出姿态 提交于 2019-11-27 19:11:36

I'm not sure you need a plugin to deal with this:

$(document).ready(function() {
    $("#image").change(function() {
        var src = $(this).val();

        $("#imagePreview").html(src ? "<img src='" + src + "'>" : "");
    });
});

I don't think there is a plugin for this, but it is fairly trivial to do "by hand"

$(document).ready(function(){
    $('#image').change(function(){
            $('#imagePreview').html('<img src="'+$('#image').val()+'"/>');
    });
});

You should add a validation for non-existent images and such. Your mileage may vary. etc.

Do you really need a plugin?

Would something simple like below work?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>JQuery Image</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
   $("#image").change(function() {
     $("#imagePreview").empty();
     if ( $("#image").val()!="" ){
        $("#imagePreview").append("<img src=\"" + $("#image").val()  + "\" />");
     }
     else{
        $("#imagePreview").append("displays image here");
     }
   });
 });
</script>
</head>
<body>
<select name="image" id="image" class="inputbox" size="1">
   <option value=""> - Select Image - </option>
   <option value="image1.jpg">image1.jpg</option>
   <option value="image2.jpg">image2.jpg</option>
   <option value="image3.jpg">image3.jpg</option>
</select>

<div id="imagePreview">
   displays image here
</div>


</body>
</html>

Alternative method with AJAX. I have not tested it, but googled about the topic. Here are some notes:

http://forums.asp.net/t/1107236.aspx

Server-side

response.contentType('image/jpeg');
response.binaryWrite(imageBytes); 

Displaying ad content from Respose.WriteFile()/ Response.ContentType

http://www.dotnetperls.com/response-writefile

Response.WriteFile usage:           10.680 s
Byte[] cache, Response.BinaryWrite:  0.094 s

I am sharing here pure javascript version to change image using dropdown :-

<html>
<head>
<title></title>
<script language="JavaScript" type="text/javascript">
var Path='http://www.domainname.com/images/';
function CngColor(obj){
index=obj.selectedIndex;
if (index<1){ return; }
document.getElementById('Img1').src=Path+obj.options[index].value;
}

</script></head>
<body>

<select onchange="CngColor(this);" >
<option >Select</option>
<option value="Zero.gif" >Zero</option>
<option value="One.gif" >1</option>
<option value="Two.gif" >2</option>
<option value="Three.gif" >3</option>
<option value="Four.gif" >4</option>
</select>

<img id="Img1" src="http://www.domainname.com/images/Blank.gif" width=100 height=100 >

</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!