I have a asp.net input box:
<asp:TextBox ID="InCL" runat="server" Text=""></asp:TextBox>
As soon as a number is entered I would like to send that value to a javascript function that updates a google gauge.
For example, user inputs 77, the google gauge immediately dynamically moves to that position.
Any help is appreciated.
Thank You.
EDIT
I'm looking at the onkeyup DOM event, is this a good way to go?
I think I'm just talking to myself on here.....
Here is a script in jQuery I used to do something very similar. It does indeed use onkeyup to set the value; it also uses onkeydown to prevent non-numeric values; and forces a default value of 0 if the user tries to leave the textbox with no value:
var updateUI = function(value) {
//set gauge
};
var textbox = $('#id_of_textbox)'
textbox.keydown(function(e) {
return validNumberKeys.indexOf(e.which) > -1;
}).keyup(function(e) {
var input = $(e.target);
if(input.val() !== '') {
updateUI(input.val());
}
}).blur(function(e) {
var input = $(e.target);
if(input.val()==='') { input.val('0'); }
updateUI(input.val());
});
var validNumberKeys = [8,9,13,16,17,18,35,36,37,38,39,40,45,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
You can do this:
<asp:TextBox ID="InCL" runat="server" onchange="YourJavaScriptFunction()" Text=""></asp:TextBox>
YourJavaScriptFunction() would then read the value out of InCL and do whatever you need to do with it.
You could also pass the value to your JavaScript like this: onchange="YourJavaScriptFunction(this.value)"
The same syntax will work with onkeyup: onkeyup="YourJavaScriptFunction()"
Related
I want to use form serialization but exclude a button and a label from the serialization.
This is a version of the javascript I have:
var saveBtn = document.getElementById("btnSaveButton");
var saveLbl = document.getElementById("lblSaveLabel");
var originalFormData = $("#MasterForm").not(saveBtn, saveLbl).serialize();
$("form :input").on('change keyup paste mouseup', function () {
var newFormData = $("#MasterForm").serialize();
if (originalFormData != newFormData) {
//some code
} else {
//some other code
}
});
See: .not(saveBtn, saveLbl)
That is not excluding the button or the label.
Can someone please help me and let me know how I can exclude the button and the label from the serialization?
What essentially happens is I switch the display from the button to the label and back depending on whether the user has made any change to the form.
UPDATE UPDATE
Thank you for the responses ... appears something is amiss ...
There might be too much html to post here ...
Using vb.net. I have a master page, within it is a page called Admin.aspx, and within that is a usercontrol called Bundles.ascx.
In the code of Bundles.ascx I have this javascript:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(prmRequest);
prm.add_endRequest(prmRequest);
function prmRequest(sender, args) {
setupFormChangeCheck("btnSaveBundle", langId);
}
In a master javascript file I have the function setupFormChangeCheck, which looks like this:
function setupFormChangeCheck(txtName, langId) {
try {
savebtnFnctn('dis', txtName, langId)
var originalFormData = $("#MasterForm").serialize();
$("form :input").on('change keyup paste mouseup', function () {
var newFormData = $("#MasterForm").serialize();
if (originalFormData != newFormData) {
savebtnFnctn('en', txtName, langId)
} else {
savebtnFnctn('dis', txtName, langId)
}
});
} catch (err) { }
}
On the same master javascript file I have the function savebtnFunction, which looks like this:
function savebtnFnctn(event, txtName, langId) {
var saveBtn = document.getElementById(txtName);
var saveLbl = document.getElementById(txtName.replace("btn", "lbl"));
if (event == 'en') {
saveBtn.style.display = "inline";
saveLbl.style.display = "none";
} else if (event == 'dis') {
saveBtn.style.display = "none";
saveLbl.style.display = "inline";
}
}
The user control is loaded dynamically, because the same page has multiple use controls and unless I load the one control dynamically, all load ... slows things down incredibly.
Loading a user control dynamically leads to serious postback challenges. So, the vast majority of the user control interactions are handled client side with jquery. For Bundle.ascx this is done in Bundle.js
SOOOOO ....
When the user control is loaded, setupFormChangeCheck fires, which runs the 'dis' (disable) event in function savebtnFnctn.
Here is the problem I noticed today as I tried the code from suggestions above.
When I interact in the Bundle uc, setupFormChangeCheck does not fire from the beginning. What first fires is this line $("form :input").on('change keyup paste mouseup', function ()
And no matter what I do, click in a textbox even without changing anything, leads this: originalFormData != newFormData to be true and the Save button remains enabled ...
I should add that all the controls in the Bundle user control are inside an updatepanel:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
Long explanation I know, sorry ... if anyone has any idea to solve this, I would be eternally grateful.
Thank you. Erik
The jQuery's .not() method takes selector, not elements.
Also, you are matching the form itself, not the inputs of it.
Since you do know the IDs of the elements to exclude, use this instead:
var data = $("#MasterForm").find("input, textarea, select").not("#btnSaveButton, #lblSaveLabel").serialize();
You select the form.
Then you select the form elements underneath.
Then you exclude the concrete elements from the collection.
Lastly you serialize the results.
NOTE: You should use strict comparison !== instead of !=.
Given the following markup:
<input name="active" type="hidden" value="0" />
<input id="active" name="active" type="checkbox" value="1" />
When the checkbox is unchecked and the form is submitted the server will get a value of "0" for the "active" param. When the checkbox is checked and the form is submitted the server will get a value of "1" for the "active" param. This works just fine.
What I want to do is capture the proper value in JavaScript based upon that. The trick, however, is I don't know if the input is a checkbox or not. As far as my script is concerned it is just acting on a set of inputs.
I have created a JSFiddle here: http://jsfiddle.net/bcardarella/5QRjF/ that demonstrates the issue.
TL;DR I want to ensure the value I capture from each input is the actual value sent to the server.
Don't know if you actually want to check for the checkbox or not, but this code works:
$(function() {
var getCheckBoxValue = function() {
if ($('[name="active"]:checkbox').attr("checked")) {
return $('[name="active"]:checkbox').val();
} else {
return $('[name="active"]').val();
}
}
var result = $('#result');
result.append($('<p/>', {text: 'Expected value 0, got: ' + getCheckBoxValue()}));
$(':checkbox')[0].checked = true;
result.append($('<p/>', {text: 'Expected value 1, got: ' + getCheckBoxValue()}));
});
Basically if the checkbox is checked, use that, otherwise, go with the default value from the hidden input.
Edit
Turned my comment into a fiddle, I've also added another field, a text field, to show better the idea behind it: http://jsfiddle.net/45qup/
Hope it helps!
Write up the click event for the checkbox..
$('#active').on('click', function(){
var isChecked = this.checked;
var val = 0;
if(isChecked){
val = 1
}
});
Try somthing like
$("form#formID :input").each(function(){
if ($(this).attr() == 'checkbox') return $(this).checked();
else return $(this).val();
});
Not sure if if I’d go with this ;) , but it works:
var getCheckBoxValue = function() {
var values = $('[name="active"]')
.filter(':checked, :hidden')
.map(function(){
return parseInt($(this).val(), 10);
}
);
return Math.max.apply(Math, values);
}
http://jsfiddle.net/Xc5H7/1/
Inspired by #Deleteman's idea, this is a slightly simpler way of doing it:
var getCheckBoxValue = function() {
var input = $('[name="active"]');
return $(input[1].checked ? input[1] : input[0]).val();
}
This assumes there's only two fields with this name, which is a sane assumption for what you're trying to do.
It also assumes the hidden field always comes before the checkbox, which again, since this is, I assume, for Rails, is a sane assumption :)
On blur of field1, field2 is set to READONLY but the cursor on my page then defaults to field2 and the cursor is located at the END of the value and when the user clicks the backspace button the value can be erased. I would like the ability to have the cursor move to the next NON-READONLY or ENABLED field on the page. Is that do-able with jQuery?
Any help/direction would be appreciated.
Here is my code:
$(function() {
$("#ARTransferForm\\:fromAccountAmt").blur(function() {
var origAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val();
var fromAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val();
// Call validation "r2" function
var modFromAccountAmount = r2(fromAccountAmount);
//alert("modFromAccountAmount = " + modFromAccountAmount);
fromAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val(modFromAccountAmount).val();
//alert ("modified fromAccountAmount = " + fromAccountAmount);
if (modFromAccountAmount != "N.aN") {
var firstChar = fromAccountAmount.charAt(0);
var fromAcctAmtLen = $("#ARTransferForm\\:fromAccountAmt").val().length;
if (firstChar == "-") {
var revFromAcctAmt = fromAccountAmount.substring(1, fromAcctAmtLen);
$("#ARTransferForm\\:toAccountAmt").val(revFromAcctAmt);
$("#ARTransferForm\\:toAccountAmt").attr("readonly", "readonly");
} else {
$("#ARTransferForm\\:toAccountAmt").val("-"+fromAccountAmount);
$("#ARTransferForm\\:toAccountAmt").attr("readonly", "readonly");
}
} else {
$("#ARTransferForm\\:fromAccountAmt").val(origAccountAmount);
$("#ARTransferForm\\:fromAccountAmt").select();
alert("Invalid From Amount Format. Use ##.## (NO commas or $ sign)");
}
});
});
Have you tried modifying tabindexes onblur, before RETURN TRUE, to control where the cursor goes? It's kind of a hack, but there you go.
Also, you could use a delegated event (perhaps on the form) to intercept and return false on any keypress events that would modify the value of any readonly input. Something like:
$('#ARTransferForm *[readonly]').live("keypress", function(event) {
// compare keycode to blacklist: backspace, perhaps delete too?
if(bKeyIsBlacklisted) {
event.preventDefault();
return false;
}
});
(Note: that is pretty pseudocodeonous. You'll want to double-check the syntax for sizzle's attribute selectors, as well as jquery's event delegation signature. And be real careful about how wide you cast your "no keys" net: try to avoid disallowing Copy and other operations performed with keyboard shortcuts. You will need to check for a modifier key to distinguish between the user trying to type "c" and Ctrl+C.
Which browser(s) are you testing this in?
I am using asp:button to create a keyboard with A-Z and 0-9 for touch screen using Java script. This keyboard is linked with one textbox. If we click one button corresponding text will be displayed on the textbox. Its working fine. I have included the autocomplete feature to this textbox using jquery JQuery Autocomplete.
Problem:
The autocomplete is not working if i my user define keyboard. How to modify my key buttons as keyboard keys[Set event keycode]? Is it possible? Is there any other way to achieve this?
Code:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="zero" runat="server" Text="0" CssClass="myclass" OnClientClick="return typeLetter(this);" TabIndex="20"/>
function typeLetter(currentbutton) {
if (previousActiveElement != null) {
if (previousActiveElement == 'antSearchText'){
var position = document.getElementById('position').value;
if (position == '') {
alert('chk position');
} else {
var existingString = document.getElementById(previousActiveElement).value;
var beforeString = existingString.substring(0, position);
var afterString = existingString.substring(position, existingString.length);
document.getElementById(previousActiveElement).value = beforeString + currentbutton.value + afterString;
setCaretPosition(document.getElementById(previousActiveElement), parseInt(position) + 1);
setCaretPosition(document.getElementById(previousActiveElement), parseInt(position) + 1);
}
}
}
return false;
}
Edit:
In autocomplete plugin the following is getting the key event, How to pass same key event by using my keys?
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
}
Try triggering the jQuery keydown/keyup event manually. I cannot recall for the life of me which one autocomplete triggers on, but here's the gist:
// your documment.getElementById(...)
jQuery('#'+previousActiveElement).keyup();
// your setCaretPosition
Try the different key events and one should cause the autocomplete to kick in.
Hope that helps!
Thanks,
Joe
Problem get solved by using the following code.
Code:
var q = document.getElementById('txtbox');
var evObj = document.createEventObject();
evObj.keyCode = 84; // [T] key
q.fireEvent('onkeydown', evObj);
Geetha.
I have previously entered value 1111, 1222, and 1333 into a HTML text input. Now if I enter 1 to the text input, it should popup a list with value 1111, 1222, and 1333 as available options. How do you trigger an event when any one of these options is selected?
I have a javascript function that performs a calculation on values entered into the text input via "onkeyup" event. This works very well if the user just enter value via keyboard. However, it does not work if the user is selecting a previously entered value from the auto popup list.
I know we can turn off the auto popup list by adding autocomplete="off" to the form/text input. But is there any solution to make it work with the auto popup list? I have tried all available event options including "onchange", but none of those works.
The HTML code is very simple:
<input id="elem_id_1" name="output" type="text" value="0" onkeyup="update();"/>
The js function is very simple too:
function update() {
var a = $('elem_id_1').value;
$('elem_id_2').value = a / 100;
}
Have you tried the onchange event? I'm not sure if it fires for auto-complete selection, but you could also try the onpropertychange event and check for the value property:
textInput.onpropertychange = function ()
{
if (event.propertyName == "value")
doCalculation();
}
This would also work on right-click->paste or right-click->cut, which wouldn't fire your calculation using your current method.
EDIT
It looks like you might have to use a combination of events and timers. Set an interval on focus of the edit and clear it on blur. I'd also use the onpropertychange for IE to make it more efficient and keep the keyup event to make it rather quick too.
//- If it's IE, use the more efficient onpropertychange event
if (window.navigator.appName == "Microsoft Internet Explorer")
{
textInput.onpropertychange = function ()
{
if (event.propertyName == "value")
doCalculation();
}
}
else
{
var valueCheck, lastValue = "";
textInput.onkeyup = function ()
{
doCalculation();
}
textInput.onfocus = function ()
{
valueCheck = window.setInterval(function ()
{
// Check the previous value against (and set to) the new value
if (lastValue != (lastValue = textInput.value))
doCalculation();
}, 100);
}
textInput.onblur = function ()
{
window.clearInterval(valueCheck);
}
}
If your calculation routine is tiny (like a simple mathematical equation), I would just leave out the previous value check and run the calculation every 100ms.