How to trigger click event in textarea?
I tried:
jquery
$(document).ready(function(){
$('#txtid').val('something');
$('#txtid').trigger('click');
});
html
<textarea id='txtid' rows='5' cols='20'></teaxtarea>
But the click is not happened. What is wrong in the code.
I tried the focus event like this
$('#txtid').focus(); //this worked
But i need to trigger a click event after getting the value to textarea.
Please help..
You have to set a click event handler first.
Edit 1: Since you try to trigger the click event within document ready, you have to declare the click event handler within the document ready event handler, even before you trigger it.
Html:
<textarea id='txtid' rows='5' cols='20'></textarea>
jQuery:
$(document).ready(function(){
$('#txtid').click(function() { alert('clicked'); });
$('#txtid').val('something');
$('#txtid').trigger('click');
});
Fiddle: http://jsfiddle.net/j03n46bf/
Edit 2:
Since you want the event to be triggered after you get a value to your textarea, Milind Anantwar is right, you have to use the onchange event:
Same Html, different jQuery:
$(document).ready(function(){
$('#txtid').change(function() { alert('Value changed'); });
$('#txtid').val('something');
$('#txtid').trigger('change');
});
Fiddle: http://jsfiddle.net/sb2pohan/
Edit 3:
After some comments:
$(document).ready(function(){
$('#txtid').click(function() { changeDiv(); });
$('#txtid').focus(); // Set Focus on Textarea (now caret appears)
$('#txtid').val('something'); // Fill content (caret will be moved to the end of value)
$('#txtid').trigger('click'); // Click Handler will be executed
});
function changeDiv() {
// do some stuff;
}
Edit 4: Working test.html (Tested in IE, FF, Chrome):
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#txtid").click(function() { changeDiv(); });
$("#txtid").focus();
$("#txtid").val("value");
$("#txtid").trigger("click");
});
function changeDiv() {
$('#changeDiv').css("background-color","red");
$('#changeDiv').html("changed content");
}
</script>
</head>
<body>
<textarea id="txtid"></textarea>
<div id="changeDiv" style="background-color: green; width: 100px; height: 100px;">start content</div>
</body>
</html>
You probable need to trigger change event:
$('#txtid').trigger('change');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With