javascript :- get all inputs from webpage and print - javascript

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");
};
}

Related

Changing input value via 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!

how to let jquery select2 disable one option dynamically?

I have some multiselect and i use jquery select2.I want to disable one option in other multiselect when this option is selected in one multiselect.
i write this code,but it does work.
$("select.multiselect").on("change", function(e) {
if(e.added){
for(var i=0;i<this.options.length;i++){
var vals = $(this).select2("val");
for(var j=0;j<vals.length;j++){
if(this.options[i].value===vals[j]){
this.options[i].selected=true;
}
}
};
}
if(e.removed){
for(var i=0;i<this.options.length;i++){
if(this.options[i].value===e.removed.id){
this.options[i].selected=false;
}
};
}
});
how to do it?
It was more complicated then I thought but here is what I came up with:
$('select.multiselect').on('change', function(e) {
// the selected values
var vals = $(this).select2("val");
// selects contains all the OTHER select forms
var selects = $('select').not('#'+$(this).attr('id'));
// loop trough all the selects
for (var i = 0; i < selects.length; i++) {
//re-enable all options before
$(selects[i]).find('option').removeAttr('disabled');
// loop trough all the values
for (var j = 0; j < vals.length; j++) {
// disabled attribute
$(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
}
}
});
Here's a fiddle if you want to see the result in action
Make sure all your select elements have a unique id.

Possibility to select specific input fields javascript

I will show you guys what I got with jsfiddles because it makes it easier to explain.
This is what kind of form setup im running right now. (Just showing you some fields, not all)
http://jsfiddle.net/XK99Z/2/
When you change the number in one of the input fields the price will immediately change too.
It uses this piece of JS for that:
function changeTotalFromCount(input) {
var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
var count = input.value;
var price = unitPrice * count;
var formattedPrice = '\u20ac ' + price.toFixed(2);
var label = input.parentNode.nextElementSibling;
label.innerHTML = '';
label.appendChild(document.createTextNode(formattedPrice));
}
When they press the submit button they will be taken to another page where the order is with their personal details, a print button and a change order button. If they press the change order button they will go back to the page like this:
http://jsfiddle.net/KPfUT/
And as you can see the price won't show next to the number anymore, but someone helped me find a solution for this problem:
function initTotals() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
changeTotalFromCount(inputs[i]);
}
}
window.onload = initTotals;
http://jsfiddle.net/7LKf7/2/
Now there is one problem, it won't work together with other input fields, like name, phone number, adres, etc.
http://jsfiddle.net/Af724/1/
I was hoping someone could help me find a solution to this maybe let JS know i only want it to run for input type="number" since all the personal details input fields are text.
I'm nowhere near experienced in JS so please let me know if you don't understand my question or you need some more information, thanks in advance!
Use document.querySelectorAll() to only select the type="number" input elements:
var numberInputs = document.querySelectorAll('input[type="number"]');
for (var i = 0; i < numberInputs.length; i++) {
changeTotalFromCount(numberInputs[i]);
}
or check the elements for their type:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute('type') == 'number')
changeTotalFromCount(inputs[i]);
}

How to put a button inside of a text entry field in a form on a website using javascript, css, html

I would like to write a greasemonkey script that make a button inside of a text entry form on some websites, so that the text entry forms would look something like this:
____________________
Username:|___________|BUTTON|
____________________
Password:|___________|BUTTON|
Is there any way I can do this with javascript, html, and css? Note that I want my greasemonkey script to work on website's who's layout I do not know, so I can't use the image repositioning trick as in this post: How do I add a "search" button in a text input field?
Okay, let's start with jQuery, since it's more concise.
$('form').each(function () {
$(this).find('input').filter(':text').each(function () {
$(this).after($('<button>').text('My Button'));
});
});
http://jsfiddle.net/xERT8/2/
Edited for non-jquery version.
Okay, here we go!
var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
var form = forms[i];
var inputs = form.querySelectorAll("input[type=text]");
for (var j = 0; j < inputs.length; j++) {
var input = inputs[j];
var button = document.createElement('button');
button.innerText = 'My Button';
input.parentNode.insertBefore(button, input.nextSibling);
}
}
http://jsfiddle.net/53QQU/6/
Hope that helps.

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