jquery: event for simulating live typing - javascript

Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.

This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/

Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});

Did you try out the keydown or keypress event?

I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});

there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>

Related

Detect when html input required true is working

I have a form
<form id="newRecord">
<input type="text" required/>
</form>
<button form="newRecord" type="submit">Submit</button>
http://codepen.io/anon/pen/EZwRjK
When the field is empty, and you click the button, you get a "Please fill out this field." pop up next to the field. Is there a way to detect if that pop up appears with JavaScript?
In HTML5, the pseudo-class :invalid is applied to any input that triggers the "This field is required" dialog box.
If you put the listener on your button, you could find out if the dialog box appeared or not by checking to see if there were any inputs marked :invalid...
$("#newRecord input[type=submit]").click(function() {
if ($("#newRecord input:invalid").length) {
//The popup appeared
} else {
//The popup did not appear
}
});
JSFiddle demo
In fact you can. You can use checkValidity() method. It returns true if the element contains a valid data.
$(function() {
$("#submit-button").click(function () {
// using jquery
console.log($("#input-text")[0].checkValidity());
// using javascript
var input = document.getElementById("input-text");
console.log(input.checkValidity());
});
});
Fiddle
Update
Seems the pop up is not showing when using type="button".
A work around I found is to use $("input").on("blur", function () { instead.
So it should be now:
$(function() {
$("input").on("blur", function () {
console.log($("#input-text")[0].checkValidity());
var input = document.getElementById("input-text");
console.log(input.checkValidity());
// checking as a whole
console.log("Form - ", $("#newRecord")[0].checkValidity());
});
});
Fiddle
REACT / NEXT.JS
In my case, it was because the 'input' tags were required and were not in the viewport (not visible) when submitting on my form.
The form was hidden when a useState was false const [isOpen, setIsOpen] = useState(false), then it was necessary to change the state to true so that the form would appear and the "fill these fields" message.
Solution was with onInvalid() property
<input onInvalid={() => setIsOpen(true)} type='radio' required />

Username Length Verification jQuery

I am attempting to create jQuery form which is automatically updated every time the user clicks.
At the moment I am working on querying if the username is correct length; if it is not, it will make the input box outlined red.
This is my current code (which does not seem to function at all).
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$(document).click(function(e) {
if (!$(e.target).closest('#jq-user-getval').length) {
if ( $('#jq-user-getval').val() != '' ) {
if( $("#jq-user-getval").val() < 4) {
$("#jq-user-getval").addClass('border-force');
}
}
}
})
})
</script>
as you can see, I have made it so that when the user clicks away from the input box, it will check if the box is empty. If it is empty, it will check if the length is less than 4 characters, then it is supposed to add a class forcing the red outline. This is not working, however.
this is the HTML, I am unsure if the problem lies here or not:
<form action="" method="post">
<input id="jq-user-getval jq-user-class" type="text" name="username">
</form>
I am trying to replicate Microsoft's "Hotmail" registration form, if you can suggest any changes.
Your id value is incorrect. Technically, id cannot contain spaces. Change your <input /> to:
<input id="jq-user-getval" class="jq-user-class" type="text" name="username" />
The way you are using .val() < 4 is also wrong. You cannot compare like that with a string:
"hello" < 4; // This is meaningless.
"hello".length < 4; // You should use this.
Use .blur() function for this:
$(function () {
$("#jq-user-getval").blur(function () {
if (this.value.trim().length !== 0 && this.value.trim().length < 4)
$(this).addClass("border-force");
});
});
If you are dynamically loading the <input />, then you can delegate the event this way:
$(function () {
$(document).on("blur", "#jq-user-getval", function () {
if (this.value.trim().length !== 0 && this.value.trim().length < 4)
$(this).addClass("border-force");
});
});
I have added .trim() for extra security, like people might get away putting spaces.
There's no real reason for you to use the .click() function anywhere here. The clicking away really triggers blur event on the <input />.
You can use Jquery Validation.
Basic Example :
<input id="username" name="username" maxlength="4" type="text" required>
$("#yourFormID).validate();
if input is not valid and then you addClass red outline
you must use errorPlacement,errorClass properties in validate() function

JQuery if certain textboxe's are empty, disable button

I've seen plenty examples of people disabling buttons if textboxes are empty but I haven't found any which will disable a button for only certain textboxes. I'm new to Jquery and I know it is pseudo coded but you can get the idea. Which Jquery function do I have to call so that it is constantly checking? And how can I use an or statement in the if clause to determine if any textbox field is empty?
if( $('#txtEvent').val.length === 0 || $("#txtID").val.length === 0)
{
$('#btnSave').attr("disabled", "disabled");
}
else
{
$('#btnSave').attr("enabled", "enabled");
}
Form Controls
<asp:TextBox ID="txtEvent" runat="server"></asp:TextBox>
< asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server"" Text="Save and Next" />
You can do it two different ways:
if (!$("#txtEvent").val()) { //undefined will yield false
//call a method! .val() not .val
$("#btnSave").attr("disabled", "disabled");
} else {
$("#btnSave").attr("enabled", "enabled");
}
Or:
if ($("#txtEvent").length > 0) {
$("#btnSave").attr("disabled", "disabled");
} else {
$("#btnSave").attr("enabled", "enabled");
}
If you want these constantly running, wrap them in:
$("#txtEvent").on("change", function() { //code });
//using the onchange event will trigger the code whenever the txtbox changes.
//you can also use onblur if you want it to trigger AFTER the txtbox loses focus
Please note you'll have to convert these into proper asp code! This is simply a logistical answer.
Try
var $empties = $('#txtEvent, #txtID').filter(function(){
return $.trim($(this).val()).length == 0
})
$('#btnSave').prop("disabled", $empties.length === 0);
Even though this is two years old question, I would like to show another way using bind. See the text 'keyup mouseup cut paste'
This will also work if you cut or paste text as well as keyboard input. Also this will work if we click the little cross in the text box to clear the text( using mouseup).
OP stated that disable a button for "only certain textboxes".
Say we have following text boxes
<input type="text" name="tbox1" id="txtbox1" />
<input type="text" name="tbox2" id="txtbox2" />
<input type="text" name="tbox3" id="txtbox3" />
<input type="text" name="tbox4" id="txtbox4" />
<input type="submit" id="btnSubmit" name="button" value="Save and Next" disabled />
If we need to enable/disable the button based on values entered in to txtBox1 OR txtBox3 then we can use this
<script>
$(document).ready(function() {
$("#txtbox1, #txtbox3").bind('keyup mouseup cut paste', function () {
var txt = $(this);
setTimeout(function () {
$('#btnSubmit').prop('disabled', $(txt).val() == '');
}, 100);
});
});
</script>
If we need to enable/disable the button only when both txtBox1 AND txtBox3 are not empty then we can use this
<script>
$(document).ready(function() {
$("#txtbox1, #txtbox3").bind('keyup mouseup cut paste', function () {
setTimeout(function () {
($('#txtbox1').val() && $('#txtbox3').val()) ? $('#btnSubmit').prop('disabled', false) : $('#btnSubmit').prop('disabled', true);
}, 100);
});
});
</script>

focus() does not seem to work after onblur()

I have a list of input fields and when I tab through them I want to loop back to the first one, but it doesn't seem to work.
Here is my HTML
<form id="form">
<input id="mon" type="text"/> Month<br>
<input id="day" type="text"/> Day<br>
<input id="num" type="text"/> Year<br>
<input id="amt" type="text"/> Amount<br>
</form>
and my javascript
window.onload=function(){
$('mon').focus();
$('amt').onblur=function(){
//Process the input fields
$('mon').focus();
}
}
function $(a){return document.getElementById(a)}
I think your onblur event handler is being called before the default handler, causing focus to shift first to input 'mon', then to whatever the browser thinks should be in focus next. Try using the onkeypress event. e.g.
window.onload=function(){
$('mon').focus();
$('amt').onkeydown = function(e) {
//check for IE weirdness
if (e === undefined && event !== undefined)
e = event;
if (e.keyCode == 9) {
$('mon').focus();
return false;
}
}
}
function $(a){return document.getElementById(a)}
Edit: onkeydown actually seems to work in more browsers
Edit 2: added IE case. IE doesn't always pass the event as an argument
For the cursor to appear on the first input box, you need to assign the value of the input box to itself (hack). Also you need to "return false" to stop the event propagation. The modified blur function is below,
<input id="mon" type="text" onfocus="this.value=this.value;" />
$('amt').onblur = function(){ $('mon').focus(); return false; }
Take a look at this fiddle. I think this is what you want to achieve.
http://jsfiddle.net/CucuIonel/7Fpu3/7/

Check with textbox

I have this question. I have a input type text and a button. Like this html:
<form id="browser-form">
<div class="filebrowser">
<input type="text" id="browser-filepath">
</div>
<div class="upload submit">
Uploaden
</div>
</form>
But the question is. When the input type is empty. Je can not click on the button. When the input type is fil. Than you can click on the button. How can i fix that?
Thanks!
Assuming I've understood your question correctly, I think you want to prevent the link from doing anything unless the input has a value. If that's correct, then you can do this:
$("#browser-submit").click(function(e) {
if(!$("#browser-filepath").val()) {
e.preventDefault();
}
});
preventDefault is a method of the event object which, as the name suggests, prevents the default action of an event (in this case, following the link).
Here's a working example of the above.
function UpdateSubmitButton() {
var oTextBox = document.getElementById("browser-filepath");
var oButton = document.getElementById("browser-submit");
if(oTextBox.value == "") {
oButton.disabled = true;
}
else {
oButton.disabled = false;
}
}
Add an onchange="UpdateSubmitButton()" section to your text box, and you might want to add onload="UpdateSubmitButton()" to your document body.
This should do the trick.

Categories