Using prototype function with key event - javascript

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.

Related

How can I catch an `on change` event in JS once one of many elements change?

So I have several input fields that trigger a function once they change their value. Is there any way I can re-write and shorten this code? I keep repeating myself..
# .js
let months_input = $('#id_months')
let salary_input = $('#id_start_salary')
let monthly_raise_input = $('#id_monthly_raise')
months_input.on('change', function () {
run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})
salary_input.on('change', function () {
run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})
monthly_raise_input.on('change', function () {
run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})
There's multiple ways you can do what you're trying to accomplish and reduce duplication.
You could wrap your inputs in some container element and allow event bubbling to handle this for you.
That might look like this
document.getElementById('foo').addEventListener('change', e => {
console.log('input changed');
});
<div id="foo">
<input id="one" />
<input id="two" />
<input id="three" />
</div>
var myInputs = document.getElementsByClassName('myInputs')
for(let i = 0; i < myInputs.length; i++){
myInputs[i].addEventListener('change', function () {
run_calculation(months_input.val(), salary_input.val(), monthly_raise_input.val())
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type = 'text' class='myInputs'>
<input type = 'text' class='myInputs'>
<input type = 'text' class='myInputs'>
You can use a class selector instead of an id and then use the "this" keyword with it to bind a function to the onchange
$(".class").on( "click", function() {
run_calculation((this).val())
})
You can give those inputs the same class name and use "for loop" .
or you can just do this:
document.getElementsByClassName("class").addEventListener("change", () =>{ })

What is the best way to enable the next Input box when another Input box is changed

I have something similar to this:
<input id="1" type="text"></input>
<input id="2" type="text" disabled></input>
When I change the contents of id="1" I want to enable id="2". I can get it to work in this format, however, I need it to be in a specific function instead of a generic input onchange event because this page has numerous inputs:
$(document).ready(function(){
$("input").change(function(){
$(this).next().prop("disabled", false); // Element(s) are now enabled.
});
});
I believe my issue is passing "this" information to be able to change the next element. I have tried the below lines of code but am unable to get them to work. Ignore the alerts I placed in there, I was just trying to see what information was passed. Also, I am passing a string with the onchange event as well.
$(el.id).next().prop("disabled", false);
function myFunction (str, el) {
var newId = el.id;
alert(newId);
$(newId).next().prop("disabled", false);
}
function myFunction (str, id) {
$(id).next().prop("disabled", false);
}
Updated Code:
function Update(str, el){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
var newId = el.id;
alert(newId);
$(newId).next().prop("disabled", false);
}
else {
}
}
};
var Info = str;
var queryString = Info;
xmlhttp.open("POST","Reduced.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(queryString);
}
Use the keyup event listener instead.
$(document).ready(function(){
$("input[type=text]").keyup(function(){
$(this).next().prop("disabled", false); // Element(s) are now enabled.
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text">
<input type="text" disabled>
<input type="text" disabled>
<input type="text" disabled>
<input type="text" disabled>

Two script keydown not detected with two forms

Hey I have a simple code with two form and two javascript. When I clicked num key 1 or 9 should be send form, and only working with last one form. If I switch javascript code and the last one will be keycode 49 (1) then numer 1 is working but num 9 not. Problem is because on the same page I had 2 separately forms
function submitForm() {
document.priceOptionForm.submit();
document.priceOptionForm.method='post';
}
document.onkeydown = function () {
if (window.event.keyCode == '49') {
submitForm();
}
}
document.getElementById("profile_price").onclick = submitForm;
function submitForm2() {
document.priceOptionForm2.submit();
document.priceOptionForm2.method='post';
}
document.onkeydown = function () {
if (window.event.keyCode == '57') {
submitForm2();
}
}
document.getElementById("profile_price2").onclick = submitForm2;
<form action="" method="post" class="priceOptionForm" name="priceOptionForm">
<input name="paypal_email" type="text" value="whatever" id="email">
</label>
Save all
</form>
<form action="" method="post" class="priceOptionForm2" name="priceOptionForm2">
<input name="paypal_email" type="text" value="whatever" id="email">
</label>
Save all
</form>
An element can only have one 'direct' event call back per event type. By using document.onkeydown a second time, you overwrite the first one. Either put all code in one callback function or (and this is recommended) use addEventListener('keydown', callbackFunction). This way you can have multiple callback per event type per element
You should do this for every event, because, even if it works now, your event code would be prone to being overwritten somewhere else.
function submitForm() {
document.priceOptionForm.method = 'post';
document.priceOptionForm.submit();
}
document.addEventListener('keydown', function(e) {
if (e.keyCode == '49') {
console.log(1)
submitForm();
}
})
document.getElementById("profile_price").addEventListener('click', submitForm);
function submitForm2() {
document.priceOptionForm2.method = 'post';
document.priceOptionForm2.submit();
}
document.addEventListener('keydown', function(e) {
if (e.keyCode == '57') {
console.log(9)
submitForm2();
}
})
document.getElementById("profile_price2").addEventListener('click', submitForm2);
<form action="" method="post" class="priceOptionForm" name="priceOptionForm">
<input name="paypal_email" type="text" value="whatever" id="email">
</label>
Save all
</form>
<form action="" method="post" class="priceOptionForm" name="priceOptionForm2">
<input name="paypal_email" type="text" value="whatever" id="email">
</label>
Save all
</form>
I think the problem is because you passed the listener directly to document.onkeydown twice. By doing that you just override the first listener of document.onkeydown by the second listener. You should add the event listeners using addEventListener so both listeners will persist.
document.addEventListener('keydown', function listenerOne () {})
document.addEventListener('keydown', function listenerTwo () {})

Why doesn't this simple Knockout.js example work?

I am playing around with Knockout.js and created this simple example: http://jsfiddle.net/JcTxT/30/
<div id="term_grp" data-role="fieldcontain"><a>Semester:</a>
<fieldset id="term_fields" data-role="controlgroup" data-type="horizontal">
<input type="radio" name="term" id="ss" value="ss" data-bind="checked: term" />
<label for="ss">Sommersemester</label>
<input type="radio" name="term" id="ws" value="ws" data-bind="checked: term" />
<label for="ws">Wintersemester</label>
</fieldset>
Term is <span data-bind="text: pommes"></span>
var aResult = {
term: ko.observable("ss"),
pommes: "TEST"
};
$(document).on('pagebeforeshow', '#mainPage', function () {
ko.applyBindings(aResult);
});
I expected one of the radio button to be checked (the one with the value "ss" but this is not the case. Does anyone know, why?
Cheers
It works, if you use:
$(function () {
ko.applyBindings(aResult);
});
And turn off jquery mobile.
I tried in your jsfiddle.
If you need jquery mobile, this link works:
http://www.codesizzle.com/jquery-mobile-radio-with-knockout-js/
OK, what needs to be done?
Add another event handler and add it to the binding:
var aResult = {
term: ko.observable("ws"),
pommes: "TEST2"
};
ko.bindingHandlers.mobileradio = {
init: function (element, valueAccessor) {},
update: function (element, valueAccessor) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
if (valueUnwrapped == $(element).val()) {
$(element).prop("checked", "true").checkboxradio("refresh");
} else {
$(element).removeProp("checked").checkboxradio("refresh");
}
}
};
$(function () {
ko.applyBindings(aResult);
});
Working fiddle: http://jsfiddle.net/JcTxT/35/

Change value of input onchange?

I am trying to create a simple JavaScript function. When someone inserts a number in an input field, the value of another field should change to that value. Here is what I have at the moment:
function updateInput(ish) {
fieldname.value = ish;
}
<input type="text" name="fieldname" id="fieldname" />
<input type="text" name="thingy" onchange="updateInput(value)" />
Somehow this does not work, can someone help me out?
You can't access your fieldname as a global variable. Use document.getElementById:
function updateInput(ish){
document.getElementById("fieldname").value = ish;
}
and
onchange="updateInput(this.value)"
for jQuery we can use below:
by input name:
$('input[name="textboxname"]').val('some value');
by input class:
$('input[type=text].textboxclass').val('some value');
by input id:
$('#textboxid').val('some value');
<input type="text" name="fieldname" id="fieldtobechanged" />
<input type="text" name="thingy" id="inputfield" />
I have used following code and it works instantly without any delay.
var timeoutID = null;
function findMember(str) {
document.getElementById("fieldname").innerHTML = str;
}
$('#inputfield').keyup(function(e){
clearTimeout(timeoutID);
timeoutID = setTimeout(findMember.bind(undefined, e.target.value), 500);
});

Categories

Resources