impossible to give focus to an input - javascript

I need your help here, because I'm out of idea
I have the following HTML5 code
<form>
<table class="main">
<tr>
<td>Volume</td>
<td><input type="text" id="Q1" onblur="updateQ(Q1)" autofocus /></td>
<td>ml </td>
<td><input type="text" id="Q2" onblur="updateQ(Q2)" /></td>
<td>ml </td>
<td><input type="text" id="Qt" onblur="updateQ(Qt)" /></td>
<td>ml </td>
</tr>
</table>
</form>
and the following javascript function
function updateQ(ident) {
var valeur = ident.value;
var inputId = ident.id.toString();
if (isNaN(valeur)) {
ident.value = "";
document.getElementById(inputId).focus();
}
}
When the page is loaded, the first < input > get the focus.
I want to check if the user is entering only number, so "onblur" I call the function, which check the content.
If it's not a number, I remove the value and I try to give back the focus to the < input >
It doesn't work !
Impossible to give back the focus, the second input have it and it never goes back to the first one
I don't see any error in the Javascript console, and the rest of the script works nicely.
Even giving the real id ("Q1") doesn't work ...
However, out of the function, giving the focus to another < input > works nicely
Any idea ?
Thanks in advance for your help
ericc

please see here http://jsbin.com/bapuyanuvula/1/
function updateQ(ident) {
var valeur = ident.value;
var inputId = ident.id.toString();
if (isNaN(valeur)) {
ident.value = "";
setTimeout(function() {
document.getElementById(inputId).focus();
}, 0)
}
}
The onblur event is happening while the user is leaving it. In some browsers this event can be canceled (i.e.: event.preventDefault()). So you can't focus it, because at this time it's still focused. So you either prevent the blur event or use a setTimeout as provided above...

This is browser related issue, Try this
function updateQ(ident) {
var valeur = ident.value;
var inputId = ident.id.toString();
if (isNaN(valeur)) {
ident.value = "";
setTimeout(function(){
document.getElementById(inputId).focus();
},
0);
}
}

Its because you are passsing the wrong reference.
change this:
onblur="updateQ(Q1)"
to this:
onblur="updateQ(this)"

Related

How to reference "this" in a function

I want to validate several input fields. The code below works fine, except for the focus method. I expect that it can not interpret the "input" variable which relates to the input location on the form. Question: How do I reference the location of the specific input, bearing in mind that there are 20+ inputs ? tks !
function validateInput(quantity,input)
{
if (quantity.value !== " ") {
if(isNaN(quantity)) {
$(".myerror_alert").append('<div class="alert alert-danger"><strong>Warning!</strong> You have entered an non valid character, go back and enter a real number </div>');
input.focus(); // THIS DOES NOT WORK
return false;
}
}
return true;
}
$(".product_table").on('change', '.edit_quantity',function (){
var quantity = $(this).parents(':eq(1)').find('input').filter(".edit_quantity").val();
var input = $(this).parents(':eq(1)').find('quantity').filter(".edit_quantity");
validateInput(quantity, input);
// MORE CODE GOES HERE //
});
HTML:
<tr class='delete_row'>
<td><input class="product_id form-control" readonly="readonly" name="product_id[0]" type="text" value="123"></td>
<td><input class="edit_product_id form-control" readonly="readonly" name="product_id[0]" type="text" value="Euroshake Blackstone"></td>
<td><input class="edit_quantity" name="product_id[0]" type="text" value="120"></td>
<td id="price"><input class="unit_price form-control" readonly="readonly" style="text-align:right;" name="price" type="text" value="120.00"></td>
<td><input class="line_cost form-control" readonly="readonly" style="text-align:right;" name="cost" type="text" value="14400.00"></td>
<td>
<span style="padding-left:12px;"><input name="delete" type="checkbox" value="123"></span>
</td>
</tr>
What I did was supose that in this part .find('quantity') you was probably meaning .find('input') as its previous statement, then I figure out that you were working with the same element there. So being the same element, you don't need to hold it's reference(in input var) and it's value(quantity var) to pass into validateInput. As this is a function, why not work with less code and make the function handles it, right? So I've changed it to pass only the element reference and inside the function with this condition if ($input.val().length > 0 && isNaN($input.val())) I could check if element ins't empty and also if it isn't a number:
function validateInput(input)
{
var $input = $(input);
if ($input.val().length > 0 && isNaN($input.val())) {
$(".myerror_alert").append('<div class="alert alert-danger"><strong>Warning!</strong> You have entered an non valid character, go back and enter a real number </div>');
input.focus();
return false;
}
return true;
}
$(".product_table").on('change', '.edit_quantity',function (){
validateInput(this);
});
Demo
One important mistake you've done that you've workaround it - probably - without noticing it, is that you navigate through the element tree to find the input, but when you do $(".product_table").on('change', '.edit_quantity' you're in fact binding an event in all elements with class edit_quantity inside the element with class product_table, so inside the event, your this already is the input, you don't need to go after it, as I did:
validateInput(this);
I hope this helps.

Javascript run onChange not onLoad

I have a very simple piece of Javascript that works perfectly onLoad, but I need it to work onChange.
My script;
<form action="" method="post" name="product_search">
<p><strong>Existing Part Number:</strong>
<input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()">
<input type="text" name="prodref" id="prodref">
<input type="submit" name="search_Submit" id="search_Submit" value="Submit">
</p>
<div>
<%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
// <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
<script>
function searchValue() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref');
if(c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add) }
else {
n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
document.getElementById("prodref").value = n_ProdRef;
}
</script>
</form>
So, I enter a part number in the first text box, and I want my javascript to run and enter the new value in the second text box, but it doesn't seem to work.
What am I missing?
search does not exist on an HTMLInputElement. You need to use c_ProdRef.value.search.
(Actually, since you're using it in many places as a string, and never as an input, you probably intended to define c_ProdRef as var document.getElementById('v_prodref').value)
You would've seen this error on load as well.
you want onkeyup if it works perfectly onLoad, and you want to start typing in something in textbox 1 and the javascript to run, you dont want onchange
onchange triggers after blur of focused element
onkeyup triggers after you release a keyboard input
Thanks to everyone for their help. After a little tweaking I have managed to get my code working.
function myFunction() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref').value;
if (c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add)
} else {
n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
}
document.getElementById("prodref").value = n_ProdRef;
}
Along with #indubitablee suggestion of onKeyup and specifying the .value of my first text field it all works.

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

Pass the value of html input text to Javascript Function and get the result

This is my very first time I'm using Javascript.
I have this Script:
<script type="text/javascript">
function baunilha()
{
var qb=document.getElementById("quantbaunilha").innerHTML;
var prbau=5.58;
var totbau=qtd*prbau;
}
document.getElementById("valorlinhab").innerHTML=baunilha();
</script>
And, this is how the Function is called:
<tr>
<td><img src="/imagens/DOB_Baunilha.PNG" style="vertical-align: middle" alt="Ima_Bau"> </td>
<td>Caixa de 42 Unidoses de Detergente Ultra-Concentrado aroma Baunilha</td>
<td><input id="quantbaunilha" name="quantbaunilha" value="0" maxlength="2" type="text" size="2" onchange="baunilha()"></td>
<td><input id="valorunib" name="valorunib" size="6" value="5.58">€</td>
<td><input id="valorlinhab" name="valorlinhab" size="8" value="0.00">€</td>
</tr>
So, I want that the result of the Function apears in text-box id="valorlinhab".
I tried the examples of w3schools, but they didn't work, as others examples in the web.
Is there someone who could help me? Any help is wellcome.
Thank you, in advance.
You need to be using value instead of innerHTML. Additionally, you are using "qtb" instead of "qb" in your calculation. You should also set the value inside the baunilha function. Finally, you must tie an event listener to the input so that it will call the javascript function.
I also added a line which would check if the input is actually a number.
function baunilha()
{
var qb=document.getElementById("quantbaunilha").value;
//check that quantbaunilha is a number
if(isNaN(parseFloat(qb)))
{
alert('Enter a number');
return;
}
var prbau=5.58;
document.getElementById("valorlinhab").value=qb*prbau;
}
document.getElementById("quantbaunilha").addEventListener('change', baunilha);
Here is a fiddle: http://jsfiddle.net/uLfcG/3/
You use innerHTML to put the results in to an element's inner HTML for a tag with both an opening and closing tag (like <p>).
Also, since you are using it for your onchange event, you should move the value setting in to the function as well.
For <input>, you set the value attribute instead:
<script type="text/javascript">
function baunilha() {
var qb=document.getElementById("quantbaunilha").value;
var prbau=5.58;
var totbau=qb*prbau;
document.getElementById("valorlinhab").value=totbau;
}
</script>
That should do the trick.
Here is a JSFiddle with a working example: http://jsfiddle.net/U7ZZh/
Also, you had a small typo on the line that is var totbau=qtb*prbau should be var totbau=qb*prbau

creating an inline update field using jquery

I've gotten stuck(again)
I have a table and one of the columns is a value that I want to be able to click, turn into an input field, then click again to change it back to just text.
I've gotten the first step done. It turns into an input field with a link to click and it uses the value that was previously in the td.
However, in writing the function to update the value and remove the input, I can't get it to fire at all. I've tried copying out the input field and hard coding that first step into the page and when I do that it does actually fire the click function. (I haven't finished writing this step as I wanted to get the function to fire first. Below is my code. Any help is overwhelmingly appreciated!
HTML:
<table>
<tr id="1"><td class="qty" set="0" >2</td></tr>
<tr id="2"><td class="qty" set="0" >2</td></tr>
<tr id="3"><td class="qty" set="0" >2</td></tr>
</table>
JQUERY:
$(".qty").click(function(){
var value = $(this).text();
var set =$(this).attr('set');
if (set==0){
$(this).html('<input type="text" name="quantity" value="'+value+'">update </span>');
$(this).attr('set', '1');
}
});
$(".update_qty").click(function(){
alert("using this to check if it's firing");
});
you need to use the live() function, otherwise the event won't be added to newly created elements.
$(".update_qty").live('click',function() {
alert("check if firing");
});
demo
http://jsfiddle.net/JEBaN/1/
some value
<br><br>
<a href='javascript:' id='toEdit'>To Edit Mode</a>
<a href='javascript:' id='toView'>To View Mode</a>​
jQuery(function(){
jQuery('#toEdit').click(_toEditMode);
jQuery('#toView').click(_toViewMode);
});
function _toEditMode()
{
var _elm=jQuery('.converter');
var _val= _elm.html();
_elm.html('<input type="text" value="'+_val+'" />');
}
function _toViewMode()
{
var _elm=jQuery('.converter');
var _val= _elm.find('input').val();
_elm.html(_val);
}
​
$(".update_qty").click(function(){
$("qty").html("<p>whatever text you want</p>");
});

Categories

Resources