Changing input value via javascript - javascript

I am trying to change input value via javascript.
Everything works fine and the input value was changed successfully in this jsfiddle - http://jsfiddle.net/webvitaly/dbv0vuhz/6/
(function () {
function form_init() {
var elements,
len,
i;
elements = document.querySelectorAll('.input');
len = elements.length;
for (i = 0; i < len; i++) {
elements[i].value = 'new value';
console.log(elements);
console.log(elements[i].value);
}
var dynamic_control = '<input type="text" class="input-dynamic" value="dynamic value" />';
elements = document.querySelectorAll('form');
len = elements.length;
for (i = 0; i < len; i++) {
//elements[i].innerHTML += dynamic_control;
}
};
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', form_init, false);
}
setTimeout(function () { // set 1 second timeout
form_init();
}, 1000);
})();
But when I am trying to add another input to the form via javascript the previous code does not work and the input value was not changed - http://jsfiddle.net/webvitaly/dbv0vuhz/5/
Can you tell me what I am doing wrong?

The HTML structure of the first input is still value="old value", the new value you set through JS, updates the DOM but in the HTML it still have "old value", so when you do this -
elements[i].innerHTML += dynamic_control; // concatenate with the input "old value" in html because in markup it's old value
the new value will not appear because in the HTML its "old value"
hope you understood what I mean, if you didn't then just right click on each fiddle input and then click inspect element from your browser, you will see in the markup saying value="old value" and showing "new value" in the first fiddle. The .innerHTML gets the HTML markup and then concatenates and finally append it.
UPDATE: The correct way of creating input as per your need will be -
/* create input element this way */
var dynamic_control = document.createElement('input');
dynamic_control.setAttribute('type', 'text');
dynamic_control.setAttribute('class', 'input-dynamic');
dynamic_control.setAttribute('value', 'dynamic value');
elements = document.querySelectorAll('form');
len = elements.length;
for (i = 0; i < len; i++) {
elements[i].appendChild(dynamic_control); // append the input element as a child of elements[i]
}
Use appendChild() instead of innerHTML.
Working Fiddle!

Related

javascript :- get all inputs from webpage and print

I'm trying to get all inputs from the webpage and to print when the user click on the input field. I want when the user focuses on the input field to type print
You have to apply onfocus on individual inputs. You are not using the index i at all.
Do this:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
inputs[i].onfocus = function() {
console.log("focus");
};
}
Easier if you can use jQuery:
$('input').focus(function(){console.log('Focus')});
Your code is almost correct. Just add [i] as done in the code below. That way your onfocus targets each input individually.
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
inputs[i].onfocus = function() {
console.log("focus");
};
}

class=ng-binding stops me from getting the textContent of an DOM element

I am creating a Chrome extension and I need to get some information from the web page.
I am trying to access the text content of a <strong class="ng-binding">Hello world</strong> element with javascript, but I get an empty string, instead of "Hello world".
I have no problem accessing other elements' content in the DOM, which doesn't have this class attribute.
How can I get the data with javascrpt from that elements?
var Tags = document.getElementsByTagName("strong");
for (var i = 0; i < Tags.length; i++) {
//print the textContent;
}
var Tags = document.getElementsByTagName("strong");
for (var i = 0; i < Tags.length; i++) {
//print the textContent;
var text = angular.element(Tags[i]).text();
console.log(text);
}

How to set input field maxlength from label

I'm trying to figure out a way to change the maxlength of ajax called input fields by pulling the value to set out of the field's label and updating the default value. The field labels all follow the same format - id, class, type and maxlength. The new maxlength value to set is always present in the id ...max_X_characters...
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029" class="gwt-
TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
So in this example I need to set the maxlength to 4.
The other problem is that there are multiple input fields, often with different maxlength values. See here for an example.
I was thinking of setting a script to pull out the value once the fields have loaded, but I don't mind admitting it, this one's over my head - hopefully one of you bright guys n gals can figure it out!
Update: Thanks for the suggestions, I've tried both, in various combinations, but can't get them to work.
Here's the code suggested by Ecwid's tech team that sets all input fields on the page to one maxlength (6 in this case)
`Ecwid.OnPageLoaded.add(function(page){if (page.type == "PRODUCT") {
$("input.ecwid-productBrowser-details-optionTextField").attr('maxlength','6');
};
})`
However, as I stated there are input fields with different maxlengths for some products.
I've tried replacing the '6' above with a function, based on your suggestions, to get the maxlength from the input id, but can't get it to work.
Any more ideas?
Thanks
Update:
Cracked it (nearly), here's the working code
`Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});`
Thanks so much for your help, it works like a dream on the product page but there is another area where it doesn't. A customer can edit the input text via a pop-up, from the shopping basket.
The fields have similar code:
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029"
class="gwt-TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
Suggestions very welcome
Chris
UPDATE:
Many, many, many thanks to ExpertSystem (you genius you!) - I think we've got it. (tested on IE10, firefox 21, chrome 27).
The code below is for people using Yola and Ecwid together, but I guess the original code may work for people using other sitebuilders. It limits the number of characters a user can enter into input fields, in Ecwid, by checking for a number in the input field's title (in this case the value between 'max' and 'characters') and replacing that as the field's maxLength value. It limits fields in the product browser, in the html widgets and in the cart pop-up.
Here it is:
Go to Yola's Custom Site Tracking Code section. In the 'Footer Code' column (actually placed at the bottom of the 'body'), place this code:
<script>
Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});
</script>
<script>
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
};
</script>
and this into the 'Header Code' column:
<script>
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
</script>
That's it! You're good to go.
It is not exactly clear what is meant by "ajax called input fields", but supposing that the input fields are created and added to DOM inside a success callback for some AJAX call, you can place the following piece of code in your pages <head>:
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
}
And then, at the end of the AJAX call's "onSuccess" callback, append this:
fixMaxLength(document);
UPDATE:
Based on your comments below, if you need to apply fixMaxLength() to div's of class "popupContent", which get dynamically added to your DOM, an easy way (not the most efficient though) would be adding a listener for DOM modification events (e.g. somewhere in <head>):
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
(NOTE: I have only tested it on latest versions of Chrome and Firefox, so I am not really sure for which other/older browsers this does work.)
(NOTE2: GGGS, has tested it (and found it working) on IE10 as well.)
How about a regular expression on your id attribute? Such as the following:
jQuery('input').each(function() {
var idVal = jQuery(this).attr('id');
var regex = /max_(\d+)_characters/g;
var result = regex.exec(idVal);
var length = result[1];
});
This is a loop over all the inputs. Once this is run, the length variable will have the proper length each go through, for your next step.

JavaScript: get custom button's text value

I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))

how can I disable everything inside a form using javascript/jquery?

I have a form that pop up inside a layer, and I need to make everything inside that form read only regarding what type of input it is. Anyway to do so?
This is quite simple in plain JavaScript and will work efficiently in all browsers that support read-only form inputs (which is pretty much all browsers released in the last decade):
var form = document.getElementById("your_form_id");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].readOnly = true;
}
With HTML5 it's possible to disable all inputs contained using the <fieldset disabled /> attribute.
disabled:
If this Boolean attribute is set, the form controls that are its
descendants, except descendants of its first optional
element, are disabled, i.e., not editable. They won't received any
browsing events, like mouse clicks or focus-related ones. Often
browsers display such controls as gray.
Reference: MDC: fieldset
You can use the :input selector, and do this:
$("#myForm :input").prop('readonly', true);
:input selects all <input>, <select>, <textarea> and <button> elements. Also the attribute is readonly, if you use disabled to the elements they won't be posted to the server, so choose which property you want based on that.
Its Pure Javascript :
var fields = document.getElementById("YOURDIVID").getElementsByTagName('*');
for(var i = 0; i < fields.length; i++)
{
fields[i].disabled = true;
}
Old question, but nobody mentioned using css:
pointer-events: none;
Whole form becomes immune from click but also hovers.
You can do this the easiest way by using jQuery. It will do this for all input, select and textarea elements (even if there are more than one in numbers of these types).
$("input, select, option, textarea", "#formid").prop('disabled',true);
or you can do this as well but this will disable all elements (only those elements on which it can be applied).
$("*", "#formid").prop('disabled',true);
disabled property can applies to following elements:
button
fieldset
input
optgroup
option
select
textarea
But its upto you that what do you prefer to use.
Old question, but right now you can do it easily in pure javascript with an array method:
form = document.querySelector('form-selector');
Array.from(form.elements).forEach(formElement => formElement.disabled = true);
1) form.elements returns a collection with all the form controls (inputs, buttons, fieldsets, etc.) as an HTMLFormControlsCollection.
2) Array.from() turns the collection into an array object.
3) This allows us to use the array.forEach() method to iterate through all the items in the array...
4) ...and disable them with formElement.disabled = true.
$("#formid input, #formid select").attr('disabled',true);
or to make it read-only:
$("#formid input, #formid select").attr('readonly',true);
Here is another pure JavaScript example that I used. Works fine without Array.from() as a NodeList has it's own forEach method.
document.querySelectorAll('#formID input, #formID select, #formID button, #formID textarea').forEach(elem => elem.disabled = true);
// get the reference to your form
// you may need to modify the following block of code, if you are not using ASP.NET forms
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
// this code disables all form elements
var elements = theForm.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].disabled = true;
}
This one has never failed me and I did not see this approach on the other answers.
//disable inputs
$.each($("#yourForm").find("input, button, textarea, select"), function(index, value) {
$(value).prop("disabled",true);
});
disable the form by setting an attribute on it that disables interaction generally
<style>form[busy]{pointer-events:none;}</style>
<form>....</form>
<script>
function submitting(event){
event.preventDefault();
const form = this; // or event.target;
// just in case...
if(form.hasAttribute('busy')) return;
// possibly do validation, etc... then disable if all good
form.setAttribute('busy','');
return fetch('/api/TODO', {/*TODO*/})
.then(result=>{ 'TODO show success' return result; })
.catch(error=>{ 'TODO show error info' return Promise.reject(error); })
.finally(()=>{
form.removeAttribute('busy');
})
;
}
Array.from(document.querySelectorAll('form')).forEach(form=>form.addEventListener('submit',submitting);
</script>
Javascript : Disable all form fields :
function disabledForm(){
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
To Enabled all fields of form see below code
function enableForm(){
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = false;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = false;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = false;
}
}
As the answer by Tim Down I suggest:
const FORM_ELEMENTS = document.getElementById('idelementhere').elements;
for (i = 0; i < FORM_ELEMENTS.length; i++) {
FORM_ELEMENTS[i].disabled = true;
}
This will disable all elements inside a form.
for what it is worth, knowing that this post is VERY old... This is NOT a read-only approach, but works for me. I use form.hidden = true.
Thanks Tim,
That was really helpful.
I have done a little tweaking when we have controls and we handle a event on them.
var form = document.getElementById("form");
var elements = form.elements;
for (var i = 0, len = elements.length; i < len; ++i) {
elements[i].setAttribute("onmousedown", "");
}

Categories