简体   繁体   中英

Put image source into closest input value

I have multiple images and multiple inputs, the input itself should have the closest image source inside it's value, i managed to put the image source inside the input's value, but they all have the same value, i want each input to take the closest image source in it's value, here is my code:

 var imgSrc = $('img').attr('src'); console.log(imgSrc); $(".test").val(imgSrc); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://www.placehold.it/1920x1080"> <input class=".test"> <img src="http://www.placehold.it/350x400"> <input class=".test"> <img src="http://www.placehold.it/950x1000"> <input class=".test"> <img src="http://www.placehold.it/500x180"> <input class=".test"> 

You will have to loop through inputs:

$(".test").each(function() {
$(this).val($(this).prev('img').attr('src'));
})

Also, you can (and you should) remove .(dot) from class names in HTML.

Demo:

 $(".test").each(function() { $(this).val($(this).prev('img').attr('src')); }) 
 input { display:block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://www.placehold.it/100x100"> <input class="test"> <img src="http://www.placehold.it/200x100"> <input class="test"> <img src="http://www.placehold.it/300x100"> <input class="test"> <img src="http://www.placehold.it/120x120"> <input class="test"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM