I didnt know how to properly name my question, but here goes.
In my html i have a "form" but not
<form></form>
.It is just a couple of selects, radio buttons and text inputs.
I enter, check and select values and according to these values, some computation is done. This "form" is computing on every keydown, blur, change. So when I change one value it will immediately recalculate the results with new value.
I would like to alert the user, when he didnt fill any of the necessary inputs. Here is how it works now (this is in a separate .js file)
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
}
$(function () {
$('select, input').on('keydown blur change', calculator);
});
I tried to put a if statement inside of my calculator function:
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
if (val1 == '' && sadzba == '' && viem == '' && ...) {
alert('You have to fill all necessary fields!')
}
}
This obviously caused, that the alert was popped every time I enter / choose new value, because at the beginning all variables are empty / with no value.
So how can I achieve, this situation: User fills in the "form" except of (for example)one value and only then will the alert pop up.
Than you.
I suggest to do the check on submit and return false if one of the fields is empty, preventing the form to be submitted.
$('form').on('submit', function () {
if (val1 == '' || sadzba == '' || viem == '') {
alert('You have to fill all necessary fields!');
return false;
} else { return true; }
});
Use a different event handler for the onblur event since that's when the cursor has left the input box. (It also prevents the event handler from firing all the time. That's a pretty expensive process and it can slow your page down)
$('select, input').on('blur', didTheyLeaveTheFieldEmpty);
Hope I understood you right, you can try this:
function calculator(event) {
if ( $(event.target).val().length == 0 ) {
alert('fill the field');
}
}
$('select, input').on('keyup', calculator);
even if you don't want a form with a submit buton you can create a button
and trigger your code on it's click
<input type="button" class="calculate">
$(function () {
$('.calculate').on('click', calculator);
});
Related
I am trying to use plain Javascript to set up a function that fires when the S key is pressed AND the search overlay is not already open AND the S is not pressed when inside an <input> or <textarea>. The issue is in the third argument and I can't seem to figure it out.
Can you please tell me how to set up the third argument in the IF statement?
I have been trying to get an equivent of the JQuery is() function in regular JS. Since I don't know much about JS I am avoiding JQuery until I get the basics down. I have created a class for OOP, so the this. is referencing that.
My Javascript:
keyPressControl(event) {
if (event.keyCode == 83 && !this.isOverlayOpen && !document.querySelectorAll('input, textarea').hasFocus()) {
this.staffSearchOpen();
}
}
The this.staffSearchOpen(); should function when all three arguments noted above are true, but I can only get the first two to work properly.
The wording of the question is a little confusing but it looks like you're trying to exclude event that happen when an input field is in focus, not the other way around.
Instead of "hasFocus()" you could just build the rule into the selector itself as input:focus, textarea:focus:
document.addEventListener('keypress', function() {
if (document.querySelector('input:focus, textarea:focus')) {
console.log("keypress event was inside an input")
} else {
console.log("No input in focus");
}
})
<input>
<textarea></textarea>
...so your function could be:
keyPressControl(event) {
if (
event.keyCode == 83 &&
!this.isOverlayOpen &&
!document.querySelector('input:focus, textarea:focus')
) {
this.staffSearchOpen();
}
}
Do it the other way around:
var elems = document.querySelectorAll('input, textarea');
elems.foreach(function (elem) {
this.addEventListener("keydown",keyPressControl);
});
keyPressControl(event) {
//you won't get a key event here unless the element is the focus owner
if (event.keyCode == ...) {
this.staffSearchOpen();
}
}
I have a few input fields that must be filled before some button becomes active. My code does this, but only works after filling all inputs fields I changed selection from last filled input field to any other. How to make it more dynamic and allow button to become active without changing selection?
$(function() {
$('body').on('change','#form2',function(){
if($("#name").val() != "" && $("#number").val() != "" && $("#shortname").val() != "")
{
$('#CreateConnections').removeAttr("disabled");
}
else
{
$('#CreateConnections').attr("disabled", true);
}
});
})
You can try binding both keyup and change to all input elements. Also:
instead of using != to evaluate the value, we can simply check the value itself: when not empty it will return true, without the need to make comparisons.
you should use .prop() when working with boolean attributes, like disabled, checked, readonly, selected and the likes, instead of .attr(). p/s: You should also avoid using .removeProp() or .removeAttr() whenever possible, as once removed they cannot be added back.
Here is the updated jQuery:
$(function() {
$('body').on('change keyup','#form2 :input', function() {
if($("#name").val() && $("#number").val() && $("#shortname").val()) {
$('#CreateConnections').prop("disabled", false);
} else {
$('#CreateConnections').prop("disabled", true);
}
});
});
Here is a proof-of-concept fiddle: http://jsfiddle.net/teddyrised/7rK2p/
I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});
I made some sort of form validation. User can input name of group and group description. With jQuery I'm validating if group name is empty or not, if empty submit button should be disabled. Now I have problems with disabling submit button. If I click on input tag where group name is, then validation is ok, and submit button is disabled, but if I just click on submit button, without touching anything else, then jQuery skip validation and fires submit button although name of group is empty.
I tried setting input tag in focus with jQuery but it only works if I actually click on that input tag.
Submit button is 'saveGroup' button.
Can someone tell me how to invoke click event on this input tag, or maybe I can use some other validation tehnique.
<div class="newGroupDiv">
<label>Title: </label><input type="text" id="groupTitle" onblur="checkTitle();"><br>
<label>Description:</label><br>
<textarea id="groupDescription"></textarea><br><br>
<button id="saveGroup">Save</button>
<button id="cancelGroup">Cancel</button>
<label id="groupError"></label>
</div>
---------------------------------------------------------------------------------
$("#saveGroup").click(function(){
var variable = checkTitle();
if(variable == true){
if($("#groupError").html() == ""){
$(".columns").append('<ul class="'+ $("#groupTitle").val() +'"><li class="naslov">'+ $("#groupTitle").val() +'</li></ul>');
$("ul").sortable({containment : 'document',
tolerance: 'pointer',
cursor: 'pointer',
revert: 'true',
opacity : 0.6,
connectWith : "ul",
placeholder: 'border',
items : 'li:not(.naslov)',
start : function(){
check = false;
$(".readContent").fadeOut(300);
}, stop : function(){
check = true;
}}).disableSelection();
$.post("addGroup.php", {'title' : $("#groupTitle").val(), 'description' : $("#groupDescription").val(),
'color' : $("#colorHex").html(), 'color2' : $("#colorHex2").html()}, function(){
window.location.reload();
});
}
}
});
--------------------------------------------------------------------------------
var checkTitle = function(){
$.post("checkTitle.php", {'title' : $("#groupTitle").val()}, function(data){
if(data == 'exist') $("#groupError").html("Group already exists");
if(data == 'no title') $("#groupError").html("Group title can't be empty");
else if(data == 'ok') $("#groupError").html("");
});
return true;
}
With this 'variable' I tried to accomplish some sort of callback wait, so when this variable gets result from function it should continue with rest of code, but I'm not sure if it works.
You would be better of switching the way you do things here. First of, as I said, make sure you do the "isEmpty" check without performing any ajax calls. Javascript is perfectly capable of doing so itself.
Secondly, instead of checking the HTML inside your element, you'd be better of checking the result of your checkTitle() function. Because there might be a slight possibility the if($("#groupError").html() == ""){ fails because there is still some HTML detected.
The above comments result in this javascript:
function checkTitle() {
$groupTitle = $('#groupTitle').val();
if($groupTitle == "") {
$("#groupError").html("Group title can't be empty");
return false;
} else {
$.post("checkTitle.php", {'title' : $groupTitle }, function(data){
if(data == 'exist') {
$("#groupError").html("Group already exists");
return false;
} else if(data == 'ok') {
$("#groupError").html("");
return true;
}
});
}
}
Now the result of the checkTitle() function can be used in your final check that you perform onBlur and onClick. Let's continue with your HTML:
<div class="newGroupDiv">
<label>Title: </label>
<input type="text" id="groupTitle" onblur="checkTitle();"><br>
<label>Description:</label><br>
<textarea id="groupDescription"></textarea><br><br>
<button id="saveGroup">Save</button>
<button id="cancelGroup">Cancel</button>
<label id="groupError"></label>
</div>
Just a little suggestion is to use a div instead of a label to show your groupError in, I understand right now this is for demo purposes only so it's just a little sidenote.
I'm not 100% possitive this solution will work, however, what I think is causing the issue is the default behaviour of the button you're using. Since the script is completely relying on the ajax call, my guess is that you have to prevent the default from happening as such:
$('#saveGroup').click(function(e) {
e.preventDefault();
});
You could give the script below a shot, hopefully it works. I can't test it because of the ajax calls. But I'll make a jsFiddle with some test data in a minute:
$("#saveGroup").click(function(e){
e.preventDefault();
var formValidation = checkTitle();
// formValidation is only true in case no errors occured
// Therefor making your #groupError check useless
if(formValidation == true) {
// Reset the #groupError html content
$('#groupError').html('');
// insert your other jQuery code here
}
});
a jsFiddle: http://jsfiddle.net/8bJAc/
As you can see onBlur the data is checked (please not there's a random factor that simulates true/false for your ajax call) and after submitting you can see either a success or error message.
I have this external jQuery code:
jQuery(document).one('keydown', 'g',function (evt){
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
return false;});
There are no errors in console.
I know it's rather silly, but never mind the text in .html(). Anyways, whenever I go to the webpage it just replaces the default 0 in the page with nothing. Then, when I press any key nothing happens. Ultimately, what I want this script to do in the end is display the letter or number that the user types in the tb div.
P.S. I'm new to stackoverflow so please tell me if my formatting is wrong or if I broke a rule.
Okay, so I edited the code and here is what I have:
$('#tb').on("keydown", function(event) {
if ($("#tb").html() == "0")
{
$("#tb").html("Testing the chicken.")
} else {$("#tb").html("Chickens fart too.")}
});
It still doesn't work.
A div element does not have a keydown event. Only element that have focus property can have it.
So I think you are referring to a input inside the div..
HTML
<div id="tb">
<span class="output"></span>
<input type="text" />
</div>
JS
// Delegating the event on input to it's container
$('#tb').on("keydown", 'input', function (event) {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
});
Check Fiddle
// Bind event to the document which fires when document is focussed and
// a key is pressed
$(document).on('keydown', function(event) {
// Key code for g
if(event.keyCode === 71) {
// Bind the event to the input when g is pressed
$('#tb input').on('keyup', inputKeydown);
// unbind the event on document as no longet necessary
$(document).off('keydown');
}
return;
});
function inputKeydown() {
// $(this).val() - Gets the value of the input on keydown
if ($(this).val() === "") {
// Set the html for span inside div
$(".output").html("Testing the chicken.");
} else {
$(".output").html("Chickens fart too.");
}
}
Another Fiddle