In ASP.NET can you String.Empty the TextBox thats IN focus? - javascript

wondering if this is possible, currently using this to click a 'clear' button, then it clears UPIN;
Protected Sub clear(ByVal Sender As Object, ByVal e As System.EventArgs)
UPIN.Text=String.Empty
End Sub
But I want it to clear whichever textbox is in focus! for example;
focusedstring.Text=String.Empty
Again is it possible without masses of JS or anything?

You should do it on client side (edit: as suggested by MightyLampshade you can find on of 1000 examples here), you do not need a round-trip to server for that. If you have, let's say, a clear button:
$("#clear").click(function() {
$(".can-be-cleared").val("");
});
Please note that this will clear all elements with class can-be-cleared (I assume you may do not want to clear each input but a specific set, if it's not the case just replace it with input[type=text]).when you click an element with id clear.
If each "clear" button has to be tied with a single specific text box then you have to repeat them (because when you click on the button textbox won't be focused any more). As alternative you may remember last focused text box. Let's see both:
<input type="text" id="textbox1"/>
<button class="clear-button" data-textbox="textbox1">clear</button>
JavaScript for this is:
$(".clear-button").click(function() {
$("#"+$(this).data("textbox")).val("");
});
Simpler alternative (I prefer this if you do not have any other special requirement) may be to keep track of last focused textbox:
var lastFocused = undefined;
$("input[type=text]").focus(function () {
lastFocused = $(this);
});
$("#clear-field").click(function () {
if (lastFocused !== undefined) {
lastFocused.val("");
}
});
Of course do not forget to match $("#clear-field") with right ID you used for your clear button, in this case I assume:
<button id="clear-field">Clear</button>
Anyway if you really need some server side processing (for any other reason), TextBox that generated event is in sender parameter:
Dim textbox As TextBox = DirectCast(sender, TextBox)
textbox.Text = String.Empty

can you try this:
$('input[type=text]').focus(function() {
$(this).val('');
});
Its simple with Jquery..no need to write masses of lines of code.
Updated:
If you do want to Clear on button click:
$("#Clear").click(function(){
$('input[type=text]').focus(function() {
$(this).val('');
});
});

Related

In HTML form, can we validate the text fields while the user is filling in the form

Is it possible to validate the text fields while user is entering the data?
For instance, If the user selects one checkbox in the form, does not enter data in the text field, and moves on to the next checkbox, the form should generate an error immediately, prompting the user to enter data for the previously selected checkbox. In other words, user will not be able to proceed unless each section
is done correctly (vs. error messages at the end of the form when the submit button is clicked)
Thank You!
There are plenty of plugins that will do this for you.
jQuery form validation plugin: This one is good
If you are determined to do it manually then you would want to use something like:
$('input').on('change', function(){...});
Here are some examples for javascript blur/focus:
https://javascript.info/focus-blur
For something you can play with, here's a jsfiddle I threw together. It uses jQuery's on focus and blur events. It checks if any of the previously "required" fields were left blank (or unchecked).
$(document).ready(function() {
function checkCheckbox(jEl) {
return jEl.is("input[type='checkbox']:checked");
}
function checkTextbox(jEl) {
return jEl.is("input[type='text']") && jEl.val() != ""
}
function validate(el) {
el.parent('div')
.prevAll('div:has(".required")')
.add(el.parent('div'))
.addClass('error')
.each((i, e) => {
jEl = $(e).children('.required');
if (checkCheckbox(jEl) || checkTextbox(jEl)) {
$(e).removeClass('error');
}
})
}
$(".required").on("focus blur", function() {
validate($(this))
});
});

How to Capture changing value of textbox

I have a webpage with a small survey. I want to pre populate some of the answers based on user inputs to previous question.
In the below code, if value of id QR~QID3 depends upon value of QID1_Total. However after the page loaded and even if the condition is met the textbox is not populated with correct value.
.addOnload(function()
{
if(document.getElementById("QID1_Total").value>15) {
document.getElementById("QR~QID3").value = "Good";
}
else{
document.getElementById("QR~QID3").value = "Average";
}
});
$("#QID1_Total").on("input", function() {
//statements goes here
});
use of on("input" will track every inputting event, include drop and paste.
know more about onInput : https://mathiasbynens.be/notes/oninput
Here is an Fiddle Example to know how trigger works :
https://jsfiddle.net/5sotpa63/
An Assumption
Let Us Say you are using a function, which holds this statement show Good and Average according to users Input.
var targetElem = document.getElementById("QID1_Total");
var showComment = (targetElem,value>15) ? "Good" : "Average";
document.getElementById("QR~QID3").value = showComment;
Above code is the shorter method of your own statement mentioned in your question.
Now on Change of the target QR~QID3 you need to load some content. you utilize the below code as follows.
$("#QR~QID3").on("input", function() {
//your next question loading statements goes here,
//statements to proceed when you show some comment Good or Average
}).trigger("input");
Hope! this could be helpful.
$('#QID1_Total').keydown(function () {
//ur code
});
as the mouse key is pressed in the input field the function is called
You need to add an event listener to the "QID1_Total" element.
If you want to run the check while the user changes the input, i.e. after each keypress use the oninput event.
If you want to run the check after the user has completed the input, use the onchange event. The onchange event will only fire after the input loses focus.
You can bind the event listeners by using the addEventListener() function like this:
document.getElementById("QID1_Total").addEventListener("input", function(){
//Code goes here
});
Here is a JSFiddle showing both methods.
You also have to use the parseInt() function on the textbox values before you can perform mathematical functions with them.

How to call a function when default browser autocomplete list item selected [duplicate]

I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.

Enable button (or any element) if at least one input has value

I'm need to enable a button (and perhaps other elements on the form in the near future) if at least one of the input element has values. I'm using BootstrapValidator as a main validation library since I'm using Twitter Bootstrap but have not idea, in the easy way, to achieve this. What I know is check each input one by one as for example:
if ($('.some_input').length > 0) { // then do actions }
But if I have many fields this solutions seems to be tedious and not very practical, also I'll need to trigger in some many events as for example: keypress, keyup, keydown, blur and maybe others too (not clear at all).
Right now the form is pretty simple as image shows below and the my solution should works but the form will grow up fast and in the near future so I leave it behind and I'm looking for another solution.
Here the button "Buscar" (it's enabled on the img but doesn't care about this I miss to disabled when I took the screenshoot) should be enabled only if any of the input on the form (Codigo de la Norma, Año de Publicacion, Palabra o Termino que contiene la Norma) has values and possibly a choice marked on the select below has a value different from the default (can be any as for example --Pick one-- with value=0) in a simple words: any input has at least 3 characters minimmum and choice in the SELECT should be different from the default one, how can I do that?
$(function() {
$(':text').on('input', function() {
if( $(':text').filter(function() { return !!this.value; }).length > 0 ) {
$('button').prop('disabled', false);
} else {
$('button').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
<button disabled="disabled">Submit</button>
</form>
Update
To expand this so it works with other form elements (excluding radios and checks) you can change :text to :input. And the code can be shortened to the following:
$(function() {
$(':input').on('input', function() {
var completed = $(':input').filter(function() { return !!this.value; }).length > 0;
$('button').prop('disabled', !completed);
});
});
Each input element has an event called change attached to it. I would add a function to run whenever this is done.
If you really want to run code whenever even one letter is added to a field, you can instead use the event known as input (be sure to check the performance of any code like this though, as it will be triggered alot!)
Although, there is much less browser support for the input event than the change one.
$('input.some_input').on('change', function() {
if ($(this).val().length > 0) {
alert('woot! text!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='some_input' value='test' />

Preventing focus on next form element after showing alert using JQuery

I have some text inputs which I'm validating when a user tabs to the next one. I would like the focus to stay on a problematic input after showing an alert. I can't seem to nail down the correct syntax to have JQuery do this. Instead the following code shows the alert then focuses on the next text input. How can I prevent tabbing to the next element after showing an alert?
$('input.IosOverrideTextBox').bind({
blur: function(e) {
var val = $(this).val();
if (val.length == 0) return;
var pval = parseTicks(val);
if (isNaN(pval) || pval == 0.0) {
alert("Invalid override: " + val);
return false;
}
},
focus: function() {
$(this).select();
}
});
I don't like forced focus, but can't you just focus after the blur takes place?
element.focus();
If doing that in the blur event doesn't always work (I'm not sure exactly when it fires, before or after the actual blur takes place), a redundant timeout will do, as well: setTimeout(function () { element.focus() }, 0).
But please don't do this. Heck, you should never be using alert or any kind of modal dialog for a web interface, either. How about adding a invalid class to the form field, putting a message off to the side of it, and disabling submit until all fields are valid? That's a much less invasive solution that allows me to fill out the form in whatever way is best for me, rather than whatever way is simplest for you.
You can do this with the validation plugin by default.
focusInvalid default: true
Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Then you'd only need to have the focus event handler do your select and let the plugin handle validation.

Categories

Resources