How to initialize form additions for jquery methods? - javascript

I've got a form where I'm trying to do the sort of thing you often see with tags: there's a textfield for the first tag, and, if you put something into it, a new and similar textfield appears to receive another tag. And so on. I've gotten the basics of this working by setting up a jQuery .blur() handler for the textfield: after the value is entered and the user leaves the field, the handler runs and inserts the new field into the form. The handler is pretty vanilla, something like:
$('input.the_field_class').blur(function () { ... });
where .the_field_class identifies the input field(s) that collect the values.
My problem is that, while the new textfield is happily added to the form after the user enters the first value, the blur handler doesn't fire when the user enters something into the newly-added field and then leaves it. The first field continues to work properly, but the second one never works. FWIW, I've watched for and avoided any id and name clashes between the initial and added fields. I had thought that jQuery would pick up the added textfield, which has the same class markings as the first one, and handle it like the original one, but maybe I'm wrong -- do I need to poke the page or some part of it with some sort of jQuery initialization thing? Thanks!

Without seeing your code in more of its context, it's hard to know for sure, but my best guess is that you're attaching a handler to the first field, but there is no code that gets called to attach it to the new field. If that's the case, you have a few options, two of which are:
1) In your blur() handler, include code to attach the blur handler to the newly created field.
2) Use jQuery's event delegation to attach a handler to the field container, and listen for blur events on any field in the container:
<div class="tag-container">
<input class="the_field_class" /> <!-- initial tag field -->
</div>
<script>
var $tagContainer = $('.tag-container');
var createNewField = function() {
$tagContainer.append($('<input class="the_field_class" />');
};
$tagContainer.on('blur', 'input.the_field_class', createNewField());
</script>
Which is better will depend on your use case, but I'd guess that the 2nd option will be better for you, since you're unlikely to be dealing with tons of blur events coming from the container.

Related

jQuery input change doesn't work

I'm trying to make something like a shopping cart, but just with an order form.
I am using this pattern to fire input changes, but it doesn't work in my case.
Here what I have first.
<div class="ingrid__table-row">
<div class="ingrid__table-data ingrid__table-item">Lemon</div>
<div class="ingrid__table-data ingrid__table-weight">15g</div>
<div class="ingrid__table-data ingrid__table-price">10</div>
</div>
With jQuery, on click, I take the data from ingrid__table-data and add to the suitable input into .order__container.
Then, on the same click, a number input is appended, which will enable to choose the quantity of the selected products.
$('.order__container').append(`<input class="bul-order-info__input bul-order-info__qnt" type="number" name="Quantity" min="1" value="1">`)
And it appears on a webpage in the order form.
I need to detect the value changes of "number type input" and fire other events.
But the input changes are not detected, although if I create the same input element manually in HTML document, these changes are detected perfectly as it's shown here
How can I achieve this behavior?
My best guess based on the info you provided is that you are trying to attach the on change event to the dynamically created inputs on this way:
$('.bul-order-info__input').change( function () {...} );
But with the code before you are aren't applying those changes to any input because none of them exists when you are creating the event handlers, so you have to bind the events to an existing element like this:
$(document).on('change', '.bul-order-info__input', function() {...});
The element doesn't have to be always document, but I tend to use it, because is the only one that always will be present. However, something like this is also valid:
$('.order__container').on('change', '.bul-order-info__input', function() {...});

angular.js: select textearea's content upon modification

I want to know if it's possible to select a textarea's content when it gets modified. In jQuery, I'd do the following:
$("texarea").on("change", function (e) {
$(this).select(); // the content gets selected for copy/cut operations
});
I know it's a bad practice to directly manipulate DOM elements from within an angular controller, so if you know how I can do this cleanly, I'd be happy to learn how!
I think you can do the following, attach an event handler to your textfield element using onblur and onfocus attributes. Write two functions for each as follows:
onfocus get the initial content of the textfield
onblur get the final content and compare to the initial content if there is a difference the run the select function
If you want it to be in real time your could also use onkeyup and onkeydown

Trigger onBlur on multiple elements as a single unit

I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.
I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.
Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.
Any suggestions on how to achieve this?
EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).
I made a working example here:
https://jsfiddle.net/bs38V/5/
It uses this:
$('#t1, #t2').blur(function(){
setTimeout(function(){
if(!$('#t1, #t2').is(':focus')){
alert('all good');
}
},10);
});
var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
focus--;
setTimeout(function() {
if (!focus) {
// both lost focus
}
}, 50);
});
An alternative approach is to check the relatedTarget of the blur event. As stated in the MDN documentation this will be the element which is receiving the focus (if there is one). You can handle the blur event and check if the focus has now been put in your other input. I used a data- attribute to identify them, but you could equally well use the id or some other information if it fits your situation better.
My code is from an angular project I've worked on, but the principle should translate to vanilla JS/other frameworks.
<input id="t1" data-customProperty="true" (blur)="onBlur($event)">
<input id="t2" data-customProperty="true" (blur)="onBlur($event)">
onBlur(e: FocusEvent){
const semanticUnitStillHasFocus = (val.relatedTarget as any)?.dataset?.customProperty === "true";
// Do whatever you like with this knowledge
}
What is the purpose of this behavior ?
The blur event triggers when a field looses focus, and only one field can gain focus at a time.
What you could do, in case of validation for instance, is to apply the same function on blur for both the fields and check the values of the fields altogether.
Without a context, it is difficult to help you more.
d.

Getting reference to form with no id or name

I am working on a project where I need to recall the fields entered in a form so I can repopulate them later. When a form has a name, I can remember it and then later use some JavaScript (document.getElementsByName(...)[0]) to access it. However, if there is no name...I'm at a loss for how to get a reference to it later.
I'm using jQuery, but am open to a JavaScript solution as well. One idea is to remember the index of the form. So, if it was document.forms[3] then later I can use the index. However, when someone submits a form, how do I know the index of the form that it is? (NOTE: I am blindly adding submit handlers to all forms when a page loads to capture the activity.)
Instead of attaching events to the submit buttons, attach it to the <form> elements directly, like this:
$("form").submit(function() {
//do something with this
//this == the form element being submitted
});
Or...in your current event handlers, use .closest() to get the closest parent <form> element:
$(":submit").click(function() {
var form = $(this).closest("form");
});
If you don't want to use an index on all form (flaky because someone may add a form in anywhere), you could use its surroundings as a reference... for example.
$('#content').parent().next().find('form')

JQuery: Finding the Object that created a DOM Element

So I've been working on this all day and I can't figure out how to get it to work. I have a table with TD's filled with content which is drawn from a database using a JQuery "getJSON" command. I have an event handler set-up so that when you double click a TD element, its contents become a INPUT element with the default value of the enclosing TD's previous contents.
The INPUT element is created inside a Javascript object named "Input" like so:
var Input = function() {
var obj = this;
obj.docElement = $('<input/>').attr('type', 'text').val(obj.defaultValue);
}
All of this is working so far. My problem is, I want the user to be able to hit the RETURN key while the INPUT is selected to signify they've finished editing that field. I've tried something like the following:
$(obj.docElement).bind('keydown', function(e) {
if(e.which == 13) {
// do something
}
}
This works fine for the first time you edit a field; however, if you edit a field multiple times it stops working. Also if you randomly double click TD's eventually it breaks. I tested it and determined that the INPUT element stops registering any type event, as if the "bind" no longer existed on it.
I've done lots of googling and determined that the regular JQuery "bind" handler placed on an INPUT element is unreliable. Therefore I decided to attach the event handler to the document object instead using the following:
$(document).bind('keydown', function(e) {
// do something
}
I know I can use "e.target" to get the target element that the action is executed on (and this works for me, e.target correctly refers to the INPUT element).
My question is, how do I get the object that created the INPUT element in the first place? I need to be able to execute functions contained within the corresponding "Input"
class that was used to create the INPUT element. I need to call these functions from within the "$(document).bind" function. So basically I need to be able to get an INPUT element's parent/creator Input object.
If I haven't explained anything clearly enough, just let me know. Any help in this matter would be greatly appreciated! I'm also open to suggestions for alternative methods (other than using "$(document).bind").
Thanks!
I think I understand the problem ...
You can traverse the DOM to find the parent document element, but that's not what you mean, right? You want the parent script element that has a bunch of logic that operates on the element.
I suspect that it is probably easiest to provide some sort of reference to the parent when the input element is created ... pass this to the event handler, or set it in a globally accessible location (like a current_element_parent var).
I agree with tobyhede. You can either add a custom attribute to the INPUT element that refers back to the parent, or keep a map in memory that maps the dynamically created INPUT element to the parent that created it. When you trap the Return key, simply remove the relationship from the map so it can be added again if the user clicks it again.

Categories

Resources