I'd like to write ajax prototype function that transforms to upper every character after typing it in a formular for several input data.
jQuery.fn.doKeyUpToUpper = function() {
$(this).val($(this).val().toUpperCase());
}
and associate this function with fields :
$('#First').doKeyUpToUpper();
$('#Second').doKeyUpToUpper();
$('#Third').doKeyUpToUpper();
where First, Second and Third are
<input id=First value="" />
<input id=Second value="" />
<input id=Third value="" />
input fields...
Unfortunately, I don't know how to add keyup event to each fields.
Anyone help ? Thanks
You where well on your way. But only defined the behaviour on "keyup" and didn't actually set the event.
jQuery.fn.doKeyUpToUpper = function () {
$(this).on('keyup', function () {
$(this).val($(this).val().toUpperCase());
});
};
// or a more dynamic alternative
jQuery.fn.toUpperOn = function (event) {
$(this).on(event, function () {
$(this).val($(this).val().toUpperCase());
});
};
// based upon the question in the comments
jQuery.fn.toUpperOn = function (event, callback) {
$(this).on(event, function () {
$(this).val($(this).val().toUpperCase());
if (callback) callback.apply(this, arguments);
});
};
$("#first").doKeyUpToUpper();
$("#second").toUpperOn('keyup');
$("#third").toUpperOn('keyup', function (event) {
console.log(this.id, this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="first" type="text" />
<input id="second" type="text" />
<input id="third" type="text" />
Have a look at the jQuery.on
documentation for more details.