I have 2 functions: the first one will update an input field, and the second one will show an image if the input value is a valid image.
I can not merge them into only one function because they are working on separated pages (I have just putted them on one page for the example). Also I can not change the first function!
Instead of .change if I use .blur or .focusout I have to click in and out the input box to update the image. How can I get it working without extra clicks?
<script type="text/javascript">
$(document).ready(function() {
$("input:radio").click(function() {
$("#image").val($(this).val());
});
});
$(document).ready(function() {
$('#image').change(function() {
var src = $(this).val();
$('#imagePreview').html(src ? '<img src="' + src + '">' : '');
});
});
</script>
<form>
<input type="radio" name="name" value="http://www.w3schools.com/images/w3schoolslogo.gif" /> IMG<br />
<input type="radio" name="name" value="http://www.google.bg/logos/classicplus.png" /> IMG<br />
<input type="radio" name="name" value="http://www.w3schools.com/images/w3schoolslogo.gif" /> IMG<br />
<input type="radio" name="name" value="http://www.google.bg/logos/classicplus.png" /> IMG<br />
<input type="radio" name="name" value="http://www.w3schools.com/images/w3schoolslogo.gif" /> IMG<br />
</form>
<input id="image" type="text" name="fname" />
<div id="imagePreview">
</div>
The
changeevent requires the following three things happen:If you are changing the value of an input programmatically, then you must manually trigger the
changeevent via jQuery’s.trigger('change')or the.change()shortcut.Ideally, you would modify the first function to trigger change:
However, per your question text, you cannot change the first function as I have suggested. This being the case, there is no good option for you, IMO. You could set up a timing interval to poll the input for its value and trigger the
changeevent if you notice that it is different from the last check, but that’s just ugly. Regardless, you need to cause the change event to fire.Ugly: