Printing field input data live with Javascript - javascript

Got a question for you javascript gurus out there. I'm creating a sidebar tool that is comprised of a few different text input fields. The purpose of this tool is to edit copy on a template. I've tried to pass the data entered into the field onchange, but I'm running into problems dumping the data into my js object. This is somewhat what I have in mind:
$('myInputField').(function(){
$(this).onChange(){
// write to variable X
}
});
Essentially I want to have what I'm typing in the input be mimicked live and then I can parse the changes to my database.

$('#myInputField').(function(){
$(this).onkeyup(){
x = this.value;
}
});
or more succinctly:
$('#myInputField').onkeyup(){
x = this.value;
});

You're just looking for the value that's in myInputField within that event handler? Something like this?:
$('myInputField').(function(){
$(this).onChange(){
x = $(this).val();
}
});
I don't remember off the top of my head if this is already a jQuery object. If it is, then this should work and perhaps skip a little bit of overhead:
x = this.val();
Additionally, you can explicitly reference the field with a normal jQuery selector if this is ever overridden with a different context, or if you want to reference other fields as well, etc.:
x = $('myInputField').val();

The problem is, on IE, the onchange event doesn't work on INPUT elements. Thus, you have to use the onkeypress or the onblur event depending on what you want to do.
JS way:
document.getElementById('myInputField').onblur = function() {
var x = this.value
}
jQuery way:
$('#myInputField').blur(function() {
var x = this.value
})

Wouldn't a simply keyup event on the input fields be sufficient?
jQuery:
$('textarea').keyup(function() {
$('#foo').html($(this).val());
});​
HTML:
<textarea></textarea>
<div id="foo"></div>
jsFiddle example.

Related

Putting a variable into a form using plain Javascript

This is pretty plain and simple but I'm just scratching my head.
I created a form (https://taa.be.wolterskluwer.com/l/940253/2021-10-08/5tgp6n) which contains a field GACLIENTID (I've assigned it the classes GA_Client_ID & GACLIENTID) however since the form is not handcoded the class is assigned to the contacting paragraph (which contains a label & input).
I've successfully pushed my variable using the following script:
<script>
(function() {
var list = document.querySelectorAll('input[name="940253_168501pi_940253_168501"]');
list.forEach(function(el){
if(el) {
el.value = {{DL - GA Client ID}};
}
})
})();
</script>
But this finds the input with the "name" of the field which changes on every clone of the form I'm creating. So I'm looking for a more "universal" way of selecting the input within the class but I just can't, for the life of me, figure out the correct syntax.
Any help is much appreciated.
var list = document.querySelectorAll('.GACLIENTID input');
If there's only ever one matching field.
const input = document.querySelector('.GACLIENTID input');
if (input) {
input.value = {{DL - GA Client ID}};
}

save subset of dom for later use preserve eventlisteners and values entered

Hello Guys is there any method I can save a part (subtree) of the DOM for later use?
What I want to achieve is the following:
I create a two forms with pure javascript.
form1 = document.createElement('form1');
input = document.createElement('input');
input.addEventListener(Listener);
form1.appendChild('input');
....
The forms are build the same way.
Somewhere I have a div in my page whereto I appendChild('form1');
Suppose I have also a button on my page. The button should switch between the forms. So when I push it I want to SAVE THE STATE OF form1 (I want to keep the eventlisteners attached and also the texts that the user entered in input fields) for example in a variable and remove(detach) after the form1 from the DOM and bind form2.
I know this could be solved with css and toggle the forms by making one hidden and the other visible but I'm in fact interested in saving the subtree of the DOM as a snapshot.
I hope you understand my question since English is not my native language.
Thanks in advance.
The button should switch between the forms. So when I push it I want
to SAVE THE STATE OF form1 (I want to keep the eventlisteners attached
and also the texts that the user entered in input fields)
The createElement creates an element and returns it as a reference which you store in a variable. Note that this is a live reference. You could take advantage of that in this use-case.
Caution: Do NOT use this on production. This is not recommended. Use simple UI/UX elements to show/hide parts of your page by way of
CSS and/or Javascript. The example below is solely to demonstrate the way things work.
Store the references to your forms in variables. Use appendChild to add those to your container. Overwrite innerHTML to remove the element from the container, and use appendChild again to swap with the other variable. All event handlers, and the input element states will be saved as-is, because of the variable being a reference.
Example: (Type different values in inputs to see state while switching.)
var forms = [],
btn = document.getElementById('btn'),
display = document.getElementById('display'),
result = document.getElementById('result'),
currentForm = 0;
;
start();
function start() {
btn.addEventListener('click', switcher);
forms[0] = createForm(0);
forms[1] = createForm(1);
display.appendChild(forms[0]);
}
function switcher() {
display.innerHTML = '';
if (currentForm === 0) {
display.appendChild(forms[++currentForm]);
} else {
display.appendChild(forms[--currentForm]);
}
}
function createForm(idx) {
var frm, inp, lbl;
frm = document.createElement('form');
inp = document.createElement('input');
inp.addEventListener('input', show);
lbl = document.createElement('label');
lbl.textContent = "Form # " + (idx + 1) + ": ";
frm.appendChild(lbl);
frm.appendChild(inp);
return frm;
}
function show(e) { result.textContent = e.target.value; }
<button id="btn">Switch</button>
<hr>
<div id="display"></div>
<hr>
<span>Keeping typing in the input above: </span><span id="result"></span>
As mentioned before, use document fragment for storing the fragments which you can refer later.
If I understand your question correctly, the Document.createDocumentFragment() is not too suitable in your case because you need to keep changes after the fragmented piece of document will be inserted into the renderer (into the "real" page's DOM)?
If so, then you could try to use experimental createHTMLDocument() and store it somewhere (in localStorage for example) what gives you the ability to synchronise both documents - your "real" one and it's copy.
But actually this question includes also avoiding superfluous repaint/reflow etc so it is a good moment to dive into documentation ;)

How to select and set multiple textboxes text in jquery

Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)

Find what specific part of the form has changed on input

I have multiple forms on my page with the following function:
$('#pageContainer').on('input propertychange change', '#form1', function() {}
Within this function, I make 11 function calls that formats text for 11 different textarea box's. I don't need to call all 11, just the one's that have changed that need formatting.
Is there a way to figure out what part of the form has been changed that made the function call so that I can call the correct (1 of 11) functions, or none at all?
So basically, if textarea 1-11 has been the input that calls the .on(), call that specific function. If not, don't call anything.
You can use event.target to find out which element caused the change event.
$('#pageContainer').on('input propertychange change', '#form1', function(e) {
var elementId = e.target.id;
//Do you actions based on this
}
I don't think there's a nice handy function to check these things, but you could assign an event handler on the onChange event, this could add $(this).attr("id") to an array. You could then construct a selector based on that array?
for example
var changes = [];
$("input").on('change', function() {
changes.push($(this).attr(id));
});
function yourFormattingFunction() {
var selector = "#" + changes.splice(", #");
$(selector).each(function() {
//...Do your formatting here
});
}
Obvious improvements like making sure the list is unique etc can be done to improve this...

jQuery keyup only keys that affects textarea content

How can I detect if the value of a textarea changes using jQuery? I'm currently using keyup() but this triggers every key stroke of course, I dont want my code to run if it's an arrow key that was pressed or any other key that doesn't have an impact on the value of the textarea.
Take a look:
$('textarea').keyup(function() {
if (content was changed)
// Do something
});
I hope you understand. How can I do this the best way? I don't want to compare the current value to an old value to check for changes, I hope that's not the only way.
By all means the easiest way is to store old values to data and do the check every keyup. The solution is quite short and will work in any case. No need to reinvent the wheel.
$("textarea").data("oldValue", function() {
return this.value;
}).keyup(function() {
var $this = $(this);
if (this.value !== $this.data("oldValue")) {
// Do something
$this.data("oldValue", this.value);
}
});
DEMO: http://jsfiddle.net/vvbSj/
$('textarea').blur(function() {
//This will be invoked when the focus is removed
});
$('textarea').change(function() {
//Same as the blur
});
Is this what you want

Categories