What I'm trying to achieve is that when tab key is pressed, the cursor will be focused on the next empty input in a grid component. Input field that has value will be skipped. If the cursor currently is in input field 2, and input field 3 has value, when tab is pressed, the cursor will jump to input field 4. This is to speed up the form entry time.
Below is the html grid component that I have created
<div class="col-md-6" id="dcNonRetainValue">
<fieldset class="ES-border frame-height-collapsed">
<legend class="ES-border">{{ 'Data Collection' }} </legend>
<collect-paged-data data="ui.dataCollectionItems" currentPage="ui.dataCollectionItemsCurrentPage" pageSize="ui.dataCollectionPageSize">
</collect-paged-data>
</fieldset>
Trying to focus next input element with js.
setTimeout(function () {
$('#dcNonRetainValue *:input:empty').focus();
}, 50);
It does not seem to work correctly. Any feedback is appreciated.
You can use filter function to select all the empty inputs. Then use eq function to select first input and use focus function. You can do like below Example:
$(document).ready(function() {
$('input').on( 'keydown', function( e ) {
if( e.keyCode == 9 ) {
const allEmptyInput = $('input').filter(function() {
return $(this).val() === "";
});
// Return if there is no Empty Input
if (allEmptyInput.length === 0) return;
e.preventDefault();
const currentInput = $(e.target);
const nextAllEmptyInput = currentInput.nextAll('input').filter(function() {
return $(this).val() === "";
});
// Focus on first input if last is focus
if (nextAllEmptyInput.length === 0) {
allEmptyInput.eq(0).focus();
return;
}
const firstEmptyInput = nextAllEmptyInput.eq(0);
firstEmptyInput.focus();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<label>First Input</label><br/>
<input type="text"/>
<br/>
<label>Second Input</label><br/>
<input type="text"/>
<br/>
<label>Third Input</label><br/>
<input type="text"/>
Using id will only give you the first element with that id. Use class instead.
Related
I have checkbox and input text and I need turn input charaters to uppercase, only when checkbox is checked.
So, if checkbox is not checked and and I type "aa", then check checkbox and type "bb", result should be: "aaBB"
I have this code but this is incorrect, as it turns entire input value to uppercase, when checkbox is checked.
$(document).ready(function() {
$('input').keyup(function() {
if ($("#ch").is(":checked")) {
this.value = this.value.toLocaleUpperCase();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ch" />
<input type="text" id="myinp" />
http://jsfiddle.net/tqa8p9ub/
You can do this with plain JavaScript using the keypress event and adding the character uppercased or not to the current input value depending on your checkbox state.
Using the keypress event is preferable to using keyup since you can intercept the key before it gets added to the input, which allows you to transform it or not or even discard it. Using keyup however forces you to change the whole input value since the value will already have been added to the input. You may also see a small flicker in this case.
Also you have to prevent the event from finishing executing by calling event.preventDefault(), otherwise the character will be added twice to the input.
You also need to insert the character at the right position using input.selectionStart. Once inserted, you have to increment both input.selectionStart and input.selectionEnd, see this answer for more details.
const checkbox = document.querySelector('#ch');
const input = document.querySelector('#myinp');
input.addEventListener('keypress', event => {
const checked = checkbox.checked;
const char = checkbox.checked ? event.key.toLocaleUpperCase() : event.key;
const pos = input.selectionStart || 0;
input.value = input.value.slice(0, pos) + char + input.value.slice(pos);
input.selectionStart = pos + 1;
input.selectionEnd = pos + 1;
event.preventDefault();
});
<input type="checkbox" id="ch" />
<input type="text" id="myinp" />
Try this -
$(document).ready(function() {
$('input').keyup(function(e) {
if ($("#ch").is(":checked")) {
let lastChar = e.key;
lastChar = lastChar.toUpperCase();
this.value = this.value.substr(0, this.value.length - 1) + lastChar;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ch" />
<input type="text" id="myinp" />
Live in action - https://jsitor.com/Q0aigCO1j
I have some code that goes through the elements that end in '_ro' as below:
document.querySelectorAll("[id$=_ro]").forEach(function(element) {
element.readOnly = true;
});
Is there a way I can check to see if there is an input, and if there is a value input, set it to read only?
Try element.nodeName == 'INPUT' to check the node name and element.value.length to check the value length:
document.querySelectorAll("[id$=_ro]").forEach(function(element) {
if(element.nodeName == 'INPUT' && element.value.length)
element.readOnly = true;
});
<input id="name_ro" type="text" value="Jhon"/>
<div id="div_ro">test</div>
<input id="phone_ro" type="text"/>
Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:
<!-- Script to prompt users to fill in the empty fields -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
</script>
This script works flawlesly and it brings up a nice prompt that looks like this:
It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.
I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...
<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
if (
document.getElementById("linux-c-arm-checkbox").checked == false &&
document.getElementById("linux-eda-cad-checkbox").checked == false &&
document.getElementById("linux-blender-checkbox").checked == false &&
document.getElementById("linux-photo-checkbox").checked == false &&
document.getElementById("linux-audio-checkbox").checked == false &&
document.getElementById("linux-latex-checkbox").checked == false &&
document.getElementById("linux-desktop-checkbox").checked == false &&
document.getElementById("linux-office-checkbox").checked == false
){
function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please choose at least one checkbox.");
}
}
}
});
</script>
Can anyone help me solve this by using javascript without JQuery?
Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.
It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.
function setAccount() {
if (document.querySelectorAll('input[name="gender"]:checked').length > 0)
document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value;
else
document.querySelector("#socialPlaceholder").value = "";
}
function invalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Please select at least one account');
} else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
<b>Accounts</b>
<input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/>
<label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label>
<label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label>
<label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label>
<label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label>
</br>
</br>
<input type="submit" value="Submit" />
<br/><br/>
NOTE: Submit without selecting any account to see the validation message
</form>
Your e is null, because you use self executing function inside if and does not pass any event for it.
Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.
In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0
I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">
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;
}