Reputation: 3086
I am building a dynamic small lenght converter that contains 3 input[text]s. Like so
<input type='text' class='bx' id='cm'> Centimeter<br>
<input type='text' class='bx' id='m'> Meter<br>
<input type='text' class='bx' id='km'> Kilometer<br>
The effect is the following: if you click on "Meter" the value becomes '' and if you type a value the "Centimeter" and "Kilometer" value will be equal to a value(...).
The jquery is like so:
$(function() {
var selected = ????;
// do i need something here to empty the input it is focused on?
$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);
})
I want the var selected to be equal to the value of the text input it is focused on.
How can i do this?
The calculation in examples are informative.
Upvotes: 0
Views: 660
Reputation: 23208
You can use jQuery focus to get selected input field.
$(function() {
$("input.bx").focus({
var selected =parseInt(this.value, 10);
this.value = ''; //this line will remove text from selected input.
$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);
});
})
Upvotes: 2
Reputation: 55750
var selected = $(this).val();
// // The code you have written will only work fro the first time your page loads. If you want it to work on every click of it you need to handle the focus event of the input..
$('#cm , #km , #m').on('focus', function() {
var selected = parseInt($(this).val() , 10) ; // Will convert to a Int
$("#cm").val(selected * 545);
$("#km").val(selected * 545);
$("#m").val(selected * 453);
});
But I think a blur event makes more sense here instead of a focus event..
Which will point to the value of the selected input
Upvotes: 1
Reputation: 665455
You need an event handler, in this case for the focus
event:
$(function() {
$(".bx").focus(function(e) {
var selectedval = this.value,
selectedtype = this.id;
…
});
});
Upvotes: 0
Reputation: 2479
You have to implement a listener that listens for the focus event.
check this out:
$('.bx').focus(function() {
var id = $(this).attr("id");
if (id === "cm") {
alert('Handler for .focus() called cm');
}
else if (id === "m") {
alert('Handler for .focus() called m');
}
else if (id === "km") {
alert('Handler for .focus() called km');
}
});
Upvotes: 0