When my JS code loads I call the following which adds a onkeypress event to all text inputs:
$('#myForm input[type=text]').keypress(function(event) {
sysOnEnter(event, $('#myForm input[type=text]').attr('id'), modalId);
});
The function sysOnEnter is to click a button when the user presses the Enter/Return key:
function sysOnEnter(event, id, modalId) {
var key = event.key || event.keyCode;
if (key == 'Enter' || key == 13) {
var val = $('#' + id).val();
setTimeout(function() {
if ($('#' + id).val() == val)
document.querySelector('#' + modalId + ' .btn-primary').click();
},0);
event.preventDefault();
return false;
}
}
The time that I don't want this to happen is when using Google's auto-suggest address form:
<input
id = "autocomplete"
class = "form-control"
placeholder = "Start typing..."
onFocus = "initAutocomplete();geolocate();"
type = "text"
>
Is there an easy way to exclude this particular field from the javascript function?
Use the selector :not(#autocomplete) to exclude the element with the autocomplete id:
$('#myForm input[type=text]:not(#autocomplete)').keypress(function(event) {
console.log('firing event');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text">
<input type="text">
<input type="text" id="autocomplete" placeholder="autocomplete">
<input type="text">
</form>
If the field you want to exclude is known beforehand you can use JQuery .not():
$('#myForm input[type=text]').not("#autocomplete").keypress(function(event) {
Related
How can I check the Number of Incomplete Input fields in Particular ID, (form1, form2).
If 2 input fields are empty, in i want a msg saying something like "Incomplete Input 2"
How is it Possible to do this in JS ?
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test">
<input type="text" value="">
</div>
This is the JS, which is working, i have have multiple JS with class named assigned to each inputs and get the value, but i need to make this check all the Input fields inside just the ID.
$(document).on("click", "#form1", function() {
var count = $('input').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
Your html structure, especially form structure is not correct, so you should first add some submit button to form that can be clicked. Then you can add event listener on form's submission. In the event handler you should select children inputs inside the form tag using $(this).children("input"). Now you can filter them.
$(document).on("submit", "#form1", function (e) {
e.preventDefault();
var count = $(this)
.children("input")
.filter(function (input) {
return $(this).val() == "";
}).length;
alert(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
<button type="submit">Submit</button>
</form>
This is the JS, which is working, if I have have multiple JS with class named assigned to each inputs and Im getting the value, but i have multiple JS for this to work.
How can i make this Simpler say like, when user clicks on Div, it only checks the input fields inside that div.
$(document).on("click", "#form1", function() {
var count = $('.input_field1').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
HTML
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="" class="input_field1">
<input type="text" value=""class="input_field1">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test" class="input_field2">
<input type="text" value="" class="input_field2">
</div>
See snippet below:
It has commented and if you put some effort on it, you can have a jQuery plugin out of it.
(function () {
'use strict';
var
// this use to prevent event conflict
namespace = 'customValidation',
submitResult = true;
var
input,
inputType,
inputParent,
inputNamePlaceholder,
//-----
writableInputTypes = ['text', 'password'],
checkboxInputType = 'checkbox';
var
errorContainerCls = 'error-container';
// Add this function in global scope
// Change form status with this function
function changeFormStatus(status) {
submitResult = submitResult && status;
}
// Check if a radio input in a
// group is checked
function isRadioChecked(form, name) {
if(!form || !name) return true;
var radio = $(form).find('input[type="radio"][name="' + name.toString() + '"]:checked');
return typeof radio !== 'undefined' && radio.length
? true
: false;
}
function eachInputCall(inp, isInSubmit) {
input = $(inp);
inputType = input.attr('type');
// assume that we have a name placeholder in
// attributes named data-name-placeholder
inputNamePlaceholder = input.attr('data-name-placeholder');
// if it is not present,
// we should have backup placeholder
inputNamePlaceholder = inputNamePlaceholder ? inputNamePlaceholder : 'input';
if(!inputType) return;
// you have three type of inputs in simple form
// that you can make realtime validation for them
// 1. writable inputs ✓
// 2. checkbox inputs ✓
// 3. radio inputs ✕
// for item 3 you should write
// another `else if` condition
// but you should have it for
// each name (it was easier if it was a plugin)
// radio inputs is not good for realtime
// unchecked validation.
// You can check radios through submit event
// let make it lowercase
inputType = inputType.toLowerCase();
// first check type of input
if ($.inArray(inputType, writableInputTypes) !== -1) {
if(!isInSubmit) {
input.on('input.' + namespace, function () {
writableInputChange(this);
});
} else {
writableInputChange(inp);
}
} else if ('checkbox' == inputType) { // if it is checkbox
if(!isInSubmit) {
input.on('change.' + namespace, function () {
checkboxInputChange(this);
});
} else {
checkboxInputChange(inp);
}
}
}
// Check if an input has some validation
// (here we have just required or not empty)
function writableInputChange(inp) {
// I use $(this) instead of input
// to prevent conflict if selector
// is a class for an input
if('' == $.trim($(inp).val())) {
changeFormStatus(false);
// your appropriate message
// you can use bootstrap's popover
// to modefy just input element
// and make your html structure
// more flexible
// or
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(inp).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please fill ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(inp).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
// Check if an checkbox is checked
function checkboxInputChange(chk) {
if(!$(chk).is(':checked')) {
changeFormStatus(false);
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(chk).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please check ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(chk).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
$(function () {
var
form = $('#form'),
// you can change this selector with your classes
formInputs = form.find('> .input-group > input');
formInputs.each(function () {
eachInputCall(this);
});
form.submit(function () {
submitResult = true;
// check all inputs after form submission
formInputs.each(function () {
eachInputCall(this, true);
});
// Because of radio grouping by name,
// we should select them separately
var selectedGender = isRadioChecked($(this), 'gender');
var parent;
if(selectedGender) {
changeFormStatus(true);
parent = $(this).find('input[type="radio"][name="gender"]').parent();
parent.children('.' + errorContainerCls).remove();
} else {
changeFormStatus(false);
// I assume that all radios are in
// a separate container
parent = $(this).find('input[type="radio"][name="gender"]').parent();
if(!parent.children('.' + errorContainerCls).length) {
parent.append($('<div class="' + errorContainerCls + '" />').text('Please check your gender'));
}
}
if(!submitResult) {
console.log('There are errors during validations!');
}
return submitResult;
});
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<div class="input-group">
<input type="text" name="input1" data-name-placeholder="name">
</div>
<div class="input-group">
<input type="checkbox" name="input2" data-name-placeholder="agreement">
</div>
<div class="input-group">
<input type="radio" name="gender">
<input type="radio" name="gender">
</div>
<button type="submit">
submit
</button>
</form>
I have created an input box, which gets validated by using the tab key, but it needs to be validated after pressing the enter key.
Here, the tick mark symbol is displayed only after I type the correct answer and then press tab. Then it goes to the next input box and also validation occurs.
But the validation needs to occur when I type the correct answer and hit the enter inside the input box itself.
For that I tried this JS code:
$(document).keypress(function(e) {
if(e.which == 13) {
checktxt(h,v,w,c)
}
});
function checktxt(h,v,w,c) {
var th=$("#"+h).val();
var tv=$("#"+v).val();
if(th.toLowerCase()==tv.toLowerCase()) {
$( "."+c ).show();
$( "."+w ).hide();
} else if(tv.toLowerCase()=="") {
} else {
$( "."+c ).hide();
$( "."+w ).show();
}
}
But also it does not get validated when I press the enter key.
And my HTML code is
<div>
<input id="texthidden1" type="hidden" value="877" />
<input id="textvisible1" type="text" value="" onblur="javascript:checktxt('texthidden1','textvisible1','wrong1','correct1');" />
<div class="wrong1"><img src="../images/smallwrong.png"/></div>
<div class="correct1"><img src="../images/smallgreen.png"/></div>
</div>
I also need the tick image to be disappeared when i erase the content of the input box.
The problem with you code is this part in your keypress listner
checktxt(h,v,w,c)
h,v,w and c are undefined here, since the code for onblur events working fine and you want to replicate the same on enter press, you need to defined these variable in you keypress event.
If you check your html , you are passing the ids of all elements to to checktxt function in your JS.
Do the same inside keypress listener as well.
$(document).keypress(function(e) {
if(e.which == 13) {
checktxt('texthidden1','textvisible1','wrong1','correct1')
}
});
$(document).keypress(function(e) {
if (e.which == 13) {
checktxt('texthidden1', 'textvisible1', 'wrong1', 'correct1')
}
});
function checktxt(h, v, w, c) {
var th = $("#" + h).val();
var tv = $("#" + v).val();
if (th.toLowerCase() == tv.toLowerCase()) {
$("." + c).show();
$("." + w).hide();
} else if (tv.toLowerCase() == "") {} else {
$("." + c).hide();
$("." + w).show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="texthidden1" type="hidden" value="877" />
<input id="textvisible1" type="text" value="" onblur="javascript:checktxt('texthidden1','textvisible1','wrong1','correct1');" />
<div class="wrong1">
<img src="../images/smallwrong.png" />
</div>
<div class="correct1">
<img src="../images/smallgreen.png" />
</div>
</div>
can someone help me with my code? everytime I type in my textbox it create multiple textbox but I want to create a program that everytime I hit enter key it create another textbox.
here's my code:
<script language="javascript">
function changeIt() {
var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i><br/>"
}
</script>
<body>
<form name="form" action="post" method="">
<input type="text" name=t1 onkeydown="changeIt()">
<div id="my_div"></div>
</form>
</body>
See this fiddle
What you have done in your code was to create a textfield whenever a key press occurs..To create a textfield only when enter key is pressed you have to check the keycode of the pressed button.
So, Please change your JS a little bit as follows..
function changeIt(event) {
var key = event.which || event.keyCode;
if (key == '13') {
var i = 1;
my_div.innerHTML = my_div.innerHTML + "<br><input type='text' name='mytext'+ i><br/>"
}
}
Please make sure that you replace your <input> also as follows
<input type="text" name=t1 onkeydown="changeIt(event)">
Please read more about keyCode in the docs.. Also, if you want to find out the keyCode of any button, please check keycode.info
Your current JS function is being execute every time a button is pressed because you're use the event onkeydown which will capture any key pressing.
Do this:
<script>
var changed = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
/* YOUR EXECUTION CODE */
}
}
</script>
<form name="form" action="post" method="">
<input type="text" name="t1">
<div id="my_div"></div>
</form>
You are creating a new <input> everytime any key is pressed. Instead, you should check if Enter was pressed using e.key or e.code (note both e.which and e.keyCode are depreacted).
Also, consider using Node.appendChild() instead of innerHTML. Otherwise, every time you add a new <input>, all the existing ones will be re-created and lose their values.
const input = document.getElementById('input');
const inputs = document.getElementById('inputs');
input.addEventListener('keydown', ({ key }) => {
if (key !== 'Enter') return;
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = `mytext${ inputs.children.length }`;
inputs.appendChild(newInput);
});
input {
display: block;
}
<form name="form" action="post" method="">
<input type="text" id="input">
<div id="inputs"></div>
</form>
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode, you can use https://keyjs.dev:
Disclaimer: I'm the author.
I have an input field and an "add" button below it. What the add button basically does is, it appends a new input field to the document. What I am trying to do here is, while typing in an input field if return key press is detected the function that calls the addition of new input field is fired the same function that is fired when the add button is clicked.
Can I incorporate the detection of return key press in the following somehow?
$('.addNewSite').on('click', function(){
var idNewInput = "site" + numInputFields;
$('.inputFieldsSettingsPanel').append('<input type="text" class="tracksiteInput" id = "' + idNewInput + '"></input>');
$("#" + idNewInput).focus();
});
I think you want this http://jsfiddle.net/naeemshaikh27/cy84t4pz/
function fun(){
$('body').append('<input type="text"/>');
}
$('.addButton').on('click', fun);
$('body').on('keypress','input', function(e){
if (e.keyCode == 13) {
fun();
}
});
something like this? e.which in the keypress() is what you're looking for to see what button is pressed. in this case, 13 is equivalent to the enter key
$(document).ready(function() {
$('.add').on('click', function() {
var html = '<input type="text" class="field" /><br/><br/>';
$('.form').append(html);
});
$(document).on("keypress", ".field", function(e) {
if(e.which == 13) {
$('.add').trigger('click');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="add" href="#">add</a><br/><br/>
<div class="form">
<input type="text" class="field" /><br/><br/>
<input type="text" class="field" /><br/><br/>
</div>
You cant detect enter keypress on the input and trigger the button's click event.
$("button").on("click", function(e){
$("body").append($("<input>").attr("type", "text"));
});
$(document).on("keypress", "input", function(e){
if(e.which == 13) $("button").trigger("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Input</button>
var i;
var inputs=document.getElementsByClassName('add');
for(i=0;i<inputs.length;i++){
inputs[i].addEventListener('keyup',function(event){
if(event.keyCode){if (event.keyCode=="13" ){createNewElem();
}}
//if(event.which){if(event.which =="13"){alert('return pressed');}}
});
}
function createNewElem(){
var newinput=document.createElement('input');
var inptype=document.createAttribute('type');
inptype.value="text";
newinput.setAttributeNode(inptype);
var inpclass=document.createAttribute('class');
inpclass.value="add";
newinput.setAttributeNode(inpclass);
document.body.appendChild(newinput);
}
<input type="text" class="add" />
I need this function to work on multiple elements in the form, right now it only works on TfDiagnosis.
How do I use it on TfDiagnosis and TfDiagnosis2 with results in TfSnowmed and TfSnowmed2?
JQUERY
$(function snowmedlist() {
$('#TfDiagnosis').on('click keyup change blur', function() {
if ($('#TfDiagnosis').val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($('#TfDiagnosis').val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
});
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2"></td>
It's easy to work on groups of elements using class names.
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="diagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
js:
$('.diagnosis').on('click keyup change blur', function() {
if($(this).val() == "...") {
$(this).next().val(1.00);
}
})
This way .next() is always the next element, so you don't need to keep passing IDs around. You can then store the data outside of the function to get rid of a cluster of IF statements:
var myData = []
myData['[D]Anterograde amnesia (780.93)'] = '206789002';
myData['[D]Chills with fever (780.60)'] = '206760004';
...then substitute the look-up from the array....
$('.diagnosis').on('click keyup change blur', function() {
$(this).next().val(myData[$(this).attr(id)]);
})
You can use
$('#TfDiagnosis, #TfDiagnosis2').on('click keyup change blur', function() {
if($(this).attr('id') == 'TfDiagnosis' ){
if ($(this).val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($(this).val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
}else{
//Stuff to do in case it is the #TfDiagnosis2
}
});
The most efficient way to make your function work on multiple inputs is to use event delegation:
$(document).on('click keyup change blur', 'input', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
Which will call the function for any input on the page. You probably want to assign a class to the specific inputs you want to use like so:
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="TfInput" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed" class="TfInput">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" class="TfInput" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2" class="TfInput">
JavaScript
$(document).on('click keyup change blur', '.TfInput', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});