function that adds <SPAN> - javascript

Good morning, I have a doubt.
I have a function that adds a click the User, the side of my input
Plus this gives an error. I wanted just once even if adicionace a person clicks the button several times the action. Do you have a scan after input if not add another
My code.
//th = Name of the input that will add, at the low <SPAN>
if(d.length == 0){
$(th).after('<SPAN class="erro">'+txt+'</SPAN>');
this.focus();
return false;
}
I would be very grateful for the help. :)

You should search for span.error first with $.find, and add it only if it isn't there already:
if(d.length == 0){
var errorSpan = $(th).find("span.error").length;
if(!errorSpan) {
$(th).after('<SPAN class="erro">'+txt+'</SPAN>');
this.focus();
}
return false;
}

use jQuery One. Attach a handler to an event for the elements. The handler is executed at most once per element.
$('#yourbuttonid').one('click', function() {
if(d.length == 0){
$(th).after('<SPAN class="erro">'+txt+'</SPAN>');
this.focus();
return false;
}
});

Register the event using $('selector').one('click', function(e) { /* your code */ }); to make it fire only once.
If th is the input name (a string), your selector should be like $('input[name='+th+']') instead of $(th)

Related

keep focus on text input field if another input field is not clicked

I am trying to create an onblur event where any time some one clicks anywhere on the page it will stay focused on that element unless it is a specif element then it will refocus to that specific element.
I am probably way off but this is what I tried, and it just stays focused on the Barcode element no matter what.
function stayOnBarcode() {
var QTY = document.getElementById("QTY");
var Barcode = document.getElementById("Barcode");
if (Barcode.value === "") {
if (QTY.focus() === true) {
QTY.focus();
}
else if (document.hasFocus() === true) {
Barcode.focus();
}
}
else {
Barcode.focus();
}
}
How about something like this:
$(document).on("mousedown", function(e) {
clicked = $(e.target)
})
$("input").on("blur", function() {
if (!clicked.is("#QTY") && !clicked.is("#Barcode")) {
$(this).focus()
}
})
It stores the most recently clicked element in the variable clicked, then on blur event it checks if last_clicked is something other than #QTY or #Barcode. If so, it re-focuses the input being blurred.
You might need to tweak it to fit the exact conditions you have in mind, or feel free to add specifics to your question.
Check out this working fiddle: https://jsfiddle.net/oez0488h/63/

jquery - Check specific inputs for empty value and add class to ONLY those inputs that are empty

I have form that has input fields that are required, I point this out with made up class name.
I have piece of code that kind of works. If I focus on required input and then press submit, that input will become red, if empty (which I want). But it only works only on one at a time and if I have focus on the input.
My code is as follows:
function checkIfEmpty(){
$('#register-form input.gv-form-required').blur(function(){
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
return false;
}else{
return true;
}
});
}
I am almost certain that the blur() method is not suitable for my situation.
So help a man out here, please.
Try this : You have to use .each() to check every input inside form and put removeClass in else condition.
function checkIfEmpty(){
var empty = false;
$('#register-form input.gv-form-required').each(function(){
if($(this).val().trim()==""){
empty = true;
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
return empty;
}
The blur event indeed doesn't seem right in your situation. What I would do is that I would itterate through each field and checked whether it is filled or not. If it is, remove (if any) has-error class. If it isn't filled, give it the has-error class
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if($(this).val() === ""){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
change your code to the following:
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if( !$(this).is(':empty')){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
try
in else condition
$(this).parent().parent().removeClass("has-error");
js code
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}

If select input equals value do this, if it is changed remove those changes

I have a select box called "requestHistoryRequestType". I'm trying to write some jQuery so that when the value of that select box is changed I call a function that adds a class and attribute to a field and appends a span to the field that I pass in as a parameter.
The problem is if a user chooses EXPAPP or EXPDEN but then changes their selection to NA it should remove the added stuff from the previous fields and add the same stuff to a different field. Kinda hard to explain, but ask questions away! I'm kinda new to writing complex jQuery like this.
The function that does the adding classes and such:
function requiredField(requiredField) {
$(requiredField).parent().addClass('has-error');
$(requiredField).attr('data-rule-required', true);
$("label[for='" + requiredField.replace('#', '') + "']").append("<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>");
}
The actual on change listener:
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
if ($("#requestHistoryRequestType").val() === "EXPAPP" || $("#requestHistoryRequestType").val() === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if ($("#requestHistoryRequestType").val() === "NA") {
requiredField("#requestHistoryComments");
}
});
Thanks Stack!
Create a function that would remove the added stuff from all fields and call it before requiredField() calls:
function removeRequiredFields()
{
var $fields = $("#requestHistoryVerbalDateTime, #requestHistoryWrittenDateTime, #requestHistoryComments");
$fields.parent().removeClass('has-error');
$fields.attr('data-rule-required', false);
$fields.each(function() {
$("label[for='"+$(this).attr('id')+"']").find("[title='Required Field']").remove();
});
}
Or you can pass $fields from the event handler to removeRequiredFields() instead of hardcoding it there, for added flexibility.
I would just have a separate function for when you select a "NA" rather then trying to build that functionality into the same function.
I'll rewrite your event handler to make it a bit cleaner as well (IMO).
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
var selectedVal = $(this).val();
if (selectedVal === "EXPAPP" || selectedVal === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if (selectedVal === "NA") {
requiredField("#requestHistoryComments");
}
});
This way you are not hitting the DOM a potential 3 time to test your conditions every time an event is triggered. A minor change but probably a useful one as you get into more complex and larger jQuery selectors.
Edit: If you feel you MUST do it in one function then you can call the function with both elements you want to append
function requiredField(requiredField1, requiredField2) {
if (requiredField2 != null){
$(requiredField1,requiredField1).parent().addClass('has-error');
$(requiredField1,requiredField1).attr('data-rule-required', true);
var requiredLabel = "<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>"
$("label[for='" + requiredField1.replace('#', '') + "']").append(requiredLabel);
$("label[for='" + requiredField2.replace('#', '') + "']").append(requiredLabel);
}
else {
//remove multiple element classes and add it to the single one representing the "NA"
}
}
This is based on you only ever having one case where you would be passing a single "requiredField" on a case of a "NA"

Phonegap - Determine exact element active

I need to change the back button functionality of my phonegap project, which I've succeeded in doing without any problem. The only issue now, is that I need to further change the functionality based on if the user has a certain field selected.
Basically, if the user has clicked in a field with the id of "date-selector1", I need to completely disable the back button.
I was attempting to use document.activeElement, but it only returns the type of the element (input in this case), but I still want the functionality to work when they are in a general input, but not when they are in an input of a specific id.
EDIT
I tried all of the suggestions below, and have ended up with the following code, but still no success.
function pluginDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
function onBackKeyDown() {
var sElement = document.activeElement;
var isBadElement = false;
var eList = ['procedure-date', 'immunization-date', 'lab-test-done', 'condition-onset', 'condition-resolution', 'medication-start-date', 'medication-stop-date', 'reaction-date'];
console.log("[[ACTIVE ELEMENT: --> " + document.activeElement + "]]");
for (var i = 0;i < eList.length - 1;i++) {
if (sElement == $(eList[i])[0]) {
isBadElement = true;
}
}
if (isBadElement) {
console.log('Back button not allowed here');
} else if ($.mobile.activePage.is('#main') || $.mobile.activePage.is('#family') || $.mobile.activePage.is('#login')) {
navigator.app.exitApp();
} else {
navigator.app.backHistory();
}
}
if you're listening for the back button you can add this if statement:
if (document.activeElement == $("#date-selector1")[0]) {
/*disable button here, return false etc...*/
}
or even better (Thanks to Jonathan Sampson)
if (document.activeElement.id === "date-selector1") {
/*disable button here, return false etc...*/
}
You can have a flag set when a user clicks on a field or you can have a click event (or any other type of event) when a user clicks on the field that should disable the back button.
From the documentation it looks like for the specific page that the backbuton is conditional on you can drop back-btn=true removing that back button.
http://jquerymobile.com/test/docs/toolbars/docs-headers.html
If you need complex conditional functionality you can just create your own button in the header or footer, style it using jquery-mobile widgets and implement your own click functionality.

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

Categories

Resources