jquery focus and auto submit after last input is filled - javascript

I have two situation with jquery,
I have two text box(name, age), now what i need to do is auto focus the name onload while the age is disabled, once user key in an input on name, it become disabled and switch with age textbox(enable and focus). once the age textbox is filled, the jquery will auto submit it w/o any button
now first things is, I am able to disable and enable the textbox, but when i put document.name.focus() its not working, I mean, the focus is not working.second things is, i manage to do the auto submit using this code
$(document).ready(function(){
$('[name="age"]').blur(function(){
if(this.value != ''){
document.form.submit();
}
});
});
so after the last textbox is filled, it will auto submit, but the problem is, I keep receive this error "Notice: Undefined index: name in C:\location" whenever i run it.
here is my code :
<script>
$(document).ready(function(){
$('[name="age"]').blur(function(){
if(this.value != ''){
document.form.submit();
}
});
});
$(document).ready(function() {
$('[name="name"]').blur(function() {
var that = $('[name="age"]')[0];
if (this.value != '') {
this.focus();
this.disabled = true;
that.disabled = false;
}
});
});
function focusName(){
var count = document.form.name.value.length + 1;
if(count <= 8){
document.form.name.focus();
}else{
document.form.age.focus();
}
}
function focusAge(){
var count = document.form.age.value.length + 1;
if(count <= 10){
document.form.age.focus()
}else{
document.form.submit();
}
}
</script>
<fieldset>
<legend>Information </legend>
<form action="receive.php" method="post" name="form">
name : <input type="text" name="name" onKeyUp="focusName();" maxlength="8"><br>
Age : <input typr="text" name="age" disabled onKeyUp="focusAge();" maxlength="3"><br>
<!--input type="submit"-->
</form>
</fieldset>
please help!!.thanks.

Few tips : add some id on your textbox
Example :
name : <input type="text" id="name" name="name" onKeyUp="focusName();" maxlength="8"><br>
Age : <input typr="text" id="age" name="age" disabled onKeyUp="focusAge();" maxlength="3">
Focus the name onload (with JQuery):
$(document).ready(function(){$("#name").focus();})
Auto submit your form :
$("form :input").focusout(function(){
$(this).each(function(){
if($(this).val()=="" )
{
return false;
}
});
$("form").submit();
});

Related

showing the length of a input

How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.

how to give "same as the above" in form entries

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form method="POST" class="form-group">
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form><br><br>
<form method="POST" class="form-group">
<label>Same as Above</label><input type="checkbox" name="chd"><br><br>
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form>
when we checked the checkbox named 'same as the above' then the second form will have to take same values that are in the first form fields.
you can use jQuery like suppose you have 2 input fields and a checkbox
if you click on checkbox it has to get value from first input and assign it to second like
$(function(){
("#checkbox").click(function(){
if($(this).is(':checked')){
var input1=$("#input1").val();
$("#input2").val(input1);
}
});
});
You need to start listening on proto form fields changes if "same as above" checked and stop listening if unchecked. And when value of any field changes then just proxy values of all proto form fields to surrogate form fields
(function($) {
var $forms = $('form');
var $protoForm = $forms.eq(0);
var $surrogateForm = $forms.eq(1);
var proxyValues = function(name) {
var $fields = $protoForm.find('input');
if (typeof name === 'string') {
$fields = $fields.filter('[name="' + name + '"]');
}
$fields.each(function() {
var field = $surrogateForm.find('[name="' + name + '"]').get(0);
if (field.type === 'checkbox') {
field.checked = this.checked;
} else {
field.value = this.value;
}
});
};
var startValuesProxy = function() {
proxyValues();
$protoForm.on('change.valuesProxy', 'input', function(e) {
proxyValues(e.target.name);
});
};
var stopValuesProxy = function() {
$protoForm.off('.valuesProxy');
};
$surrogateForm.on('change', '[name="chd"]', function(e) {
if (e.target.checked) {
startValuesProxy();
} else {
stopValuesProxy();
}
});
})(jQuery);
1) When You check the checkbox, which would mean you would need to create a hidden field on your Address form, and have the results of the address form fields that you require passed to the hidden fields on the address form.
2) On Checked Box Checked Event. Example
Hope Its Work !!!
In my experience you can just disable the controls - seems to be that way on other sites - then in your submit method - if the checkbox is clicked - send that to the controller and use the 'above' values there too..
$(function() {
$('#chkSameAsAbove').on('change', function() {
var otherControls = $(this).parent().find('input:not(#chkSameAsAbove)');
if($(this).is(':checked')) {
otherControls.prop('disabled', true);
} else {
otherControls.prop('disabled', false);
}
});
});
https://jsfiddle.net/7xv5bv4h/
Get all the inputs in javascript.
Let's say you have two input fields and one checkbox, if checkbox is checked both field will have same value, if not user will enter second value in second input.
so lets try this code:
var input1 = document.getElementById("input1");
if (document.getElementById('checkbox_field_ID').checked) {
$('#input2').append(input1);
}
I hope it helps :)

Execute code when textboxes have data

I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});

jQuery/JS Input verification

This is my simple form. I want to validate both inputs if it has some value inserted and that value is not a spaces. How can I achieve such functionality before request gets submitted to server side? Thanks a lot!
<form:form method="post" action ="${addQueryOverride}">
<label>Enter query string and product list ID: </label>
<input maxlength="30" class="text span-1" name="queryOverride" id="queryOverrideId"/>
<input onkeypress="return isNumberKey(event)" maxlength="30" class="text span-1" name="productList" id="productListId"/>
<input type="submit" value="Add">
</form:form>
$(function() { // when page load
$("form").on("submit",function(e) {
if ($.trim($("#queryOverrideId").val()) == "") {
alert("Please enter query");
$("#queryOverrideId").focus();
return false;
}
var id = $("#productListId").val();
if ($.trim(id) == "" || isNaN(id)) {
alert("Please enter product list");
$("#productListId").focus();
return false;
}
});
});
On submit, iterate over each of the fields and run a check:
$("form input:text").each(function() {
var isValid = this.value.length > 0 && this.value.indexOf(" ") == -1;
return isValid; //if true, go to next element, if false, break each loop
});

How to validate if textbox value is empty in a series of textboxes?

There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}

Categories