javascript: call function by classname - javascript

Trying to create a script that is bound by className and calls another function.
I have this code working for first instance of className, but if I remove the [0] in the first line of the script it no longer works.
<input type="text" value="NOTBound" class="NOTBound"/>
<input type="text" value="Bound value 1" class="Bound"/>
<input type="text" value="NOTBound" class="NOTBound"/>
<input type="text" value="Bound value 2" class="Bound"/>
<script>
inputBound = document.getElementsByClassName('Bound')[0];
inputBound.onfocus = function() {
var input = this.value;
formFunct(input);
}
function formFunct(input) {
console.log('done did the form Funct: ' + input)
}
</script>
How do I get it to work for all inputs with className="Bound"? I do not need a jQuery solution.
Thank you.

Use a loop to iterate all elements.
Use Array#forEach, forEach() method executes a provided function once per array element.
Another alternate could to use Array.from over HTMLCollection returned by getElementsByClassName so that you can invoke Array# methods directly over returned result.
var inputBound = document.getElementsByClassName('Bound');
[].forEach.call(inputBound, function(inputBound) {
inputBound.onfocus = function() {
var input = this.value;
formFunct(input);
}
})
function formFunct(input) {
console.log('done did the form Funct: ' + input)
}
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 1" class="Bound" />
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 2" class="Bound" />
Notes:
Refer What does [].forEach.call() do in
JavaScript?
to understand [].forEach.call.
As suggested in comments, you can use for-loop as well to iterate
HTMLCollection.
As far as Browser
compatibility
is concerned, one could use
Polyfill

Iterate over NodeList and attach event handler to the element.
// get all elements and convert to array
Array.from(document.getElementsByClassName('Bound'))
// iterate overa array elements
.forEach(function(ele) {
// bind event handler
ele.onfocus = function() {
var input = this.value;
formFunct(input);
}
});
function formFunct(input) {
console.log('done did the form Funct: ' + input)
}
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 1" class="Bound" />
<input type="text" value="NOTBound" class="NOTBound" />
<input type="text" value="Bound value 2" class="Bound" />

simply iterate all the Node(s) in a NodeList (with a good old for-loop :))
inputBounds = document.getElementsByClassName('Bound');
for( var counter = 0; counter < inputBounds.length; inputBounds++ )
{
inputBounds.item( counter ).onfocus = function() {
var input = this.value;
formFunct(input);
}
}

Related

Select all input elements that have a specific value and change their value with Javascript

I dabble in Javascript for very basic tasks everyone now and then, but for the most part I'm basically a newbie. I have a page, which has multiple input elements, which all contain unique IDs, and I want to write a script that will find a collection of inputs that contain the same value, and apply a new value to all of those selected inputs. The script I have created can accomplish this by using getElementById, but this method is no good because all of my IDs are unique. I tried using getElementsByTagName('input').value, but that doesn't seem to work. The following is my code:
<input type="text" value="Original Value 1" id="input-1">
<br>
<input type="text" value="Original Value 1" id="input-2">
<br>
<input type="text" value="Original Value 2" id="input-3">
<br>
<input type="text" value="Original Value 2" id="input-4">
<script>
function change_input_value(){
var x = document.getElementById('input-1');
if(x.value = 'Original Value 1'){
x.value = 'New Value 1';
}
}
window.onload = change_input_value();
</script>
There are 3 problems:
getElementsByTagName('input') returns an array like object, you need to iterate over it.
You used the assignment operator = instead of the comparison operator ==
The last error is not causing an a problem but it should read window.onload = change_input_value instead, that assigns the change_input_value to the onload handler. You were calling change_input_value() and assigning its return (undefined) to window.onload. It worked because when your function was called, the HTML your function relied on was already rendered
<input type="text" value="Original Value 1" id="input-1">
<br>
<input type="text" value="Original Value 1" id="input-2">
<br>
<input type="text" value="Original Value 2" id="input-3">
<br>
<input type="text" value="Original Value 2" id="input-4">
<script>
function change_input_value() {
var inputs = document.getElementsByTagName('input');
for (const input of inputs) {
if (input.value == 'Original Value 1') {
input.value = 'New Value 1';
}
}
}
change_input_value();
</script>
You have confused the = (assignment) and the == (equality test) operators.
Also, attaching the eventhandler to onload in the way you do assigns the result of the call to the function as the onload handler. This is not what you want, you want the function to be executed as the handler:
Replace
window.onload = foo(); // foo gets executed, return value is assigned
With
window.onload = foo; // foo gets assigned to 'onload' property of 'window'
Or even better, use https://developer.mozilla.org/en-US/docs/Web/API/EventListener
Two ways:
Using .querySelectorAll() and the input[value="Original Value 2"] CSS selector which selects all input elements with the value "Original Value 2":
function change_input_value() {
var x = document.querySelectorAll('input[value="Original Value 2"]');
x.forEach(function(e) {
e.value = 'New Value 1';
})
}
window.onload = change_input_value();
<input type="text" value="Original Value 1" id="input-1">
<br>
<input type="text" value="Original Value 1" id="input-2">
<br>
<input type="text" value="Original Value 2" id="input-3">
<br>
<input type="text" value="Original Value 2" id="input-4">
Use .forEach() to loop through the NodeList.
Selecting all inputs and checking the values correspondingly
function change_input_value() {
var x = document.getElementsByTagName("input");
for (let i = 0; i < x.length; i++) {
let e = x[i];
if (e.value == 'Original Value 2') {
e.value = 'New Value 1';
}
}
}
window.onload = change_input_value();
<input type="text" value="Original Value 1" id="input-1">
<br>
<input type="text" value="Original Value 1" id="input-2">
<br>
<input type="text" value="Original Value 2" id="input-3">
<br>
<input type="text" value="Original Value 2" id="input-4">

How to get all labels and its input elements in javascript

I would like to get all labels and its input elements using Javascript.
I have also radio, checkboxes and textarea elements.
Then I want to put it in an array of objects.
This is what I have done,
var html = data;
var array = [];
for(var i=0;i<$("input").length;i++){
array[i] = {label:"",val:$("input").eq(i).val()};
}
console.log(array);
By the way, doesn't have for attributes and also their next sibling is not always the input/radio/checkbox/textarea element. Sometimes,the structures are,
<label>Something:</label><Br/ ><input type="text" />
How can I do what I want in this situation?
You can use map() method to generate the array and use prevAll() method with jQuery :first pseudo-class selector to get the label(you can't use prev() method since there is a br tag in between).
var array = $("input").map(function(){
return {
label : $(this).prevAll('label:first').text(),
val:$(this).val()
};
}).get();
console.log(array);
FYI : If the input is wrapped by label in some case then you can use closest() method to get the wrapped element. Although you can use :input to select all form elements.
var array = $(":input").map(function() {
return {
label: $(this).prevAll('label:first').text(),
val: $(this).val()
};
}).get();
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Some</label>
<Br/>
<input type="text" value="1" />
<label>Some1</label>
<Br/>
<input type="text" value="11" />
<label>Some2</label>
<Br/>
<input type="text" value="2" />
<label>Some3</label>
<Br/>
<input type="text" value="4" />
<label>Some4</label>
<Br/>
<input type="text" value="3" />
<label>Some422</label>
<Br/>
<select><option value="1"></option><select>
You're using labels wrong so I'm going to assume what you really want is just some identifying attribute of the text field checkbox etc to associate with the value.
Here is my go
https://jsfiddle.net/1akh5qg9/
HTML
<form id="test-form">
<label>Label1:</label>
<input class="get-value" name="input1" type="text" />
<br>
<label>Label2:</label>
<input class="get-value" name="input2" type="text" />
<br>
<label>Label3:</label>
<input class="get-value" type="checkbox" name="checkbox1">I have a bike
<br>
<br>
<button id="submit-button">Get Values</button>
</form>
Javascript
let btn = document.getElementById('submit-button');
let form = document.forms['test-form'].getElementsByClassName('get-value');
let valueArr = [];
// attach onclick handler
btn.onclick = function(e) {
e.preventDefault();
getFormValues();
}
// getFormValues
function getFormValues() {
for (var x of form){
valueArr.push({label:x.name ,value:x.value})
}
console.log(valueArr);
}
Results
[
{label:"input1", value:"test1"},
{label:"input2", value:"test1"},
{label:"checkbox1", value:"on"}
]
For you to get the label tags in your HTML form you first have to get the label tag from the DOM and follow up with the code below:
// get array of label tags in the DOM
const label = document.getElementsByTagName("label")
for (k = 0; k < label.length; k++){
const labelText = Array.prototype.filter
.call(label[k].childNodes, x => x.nodeName === "#text")
.map(x => x.textContent)
console.log(labelText)
}
If you want to select all elements (labels, inputs) into a single array, try using a custom attribute and use a selector like this $('*[data-all-labels-inputs]');
I would recommend doing something up-front in the HTML to mark the items you want to get.
You could put the label and input pairs in a DIV to indicate that they go together and then give the DIV a class that you could filter and loop on.
You could also use data-tag attributes to name the pairs. Say give all the labels and inputs the attribute data-LabelInp="NameA". Then you can select all labels with attribute data-LabelInp, get the value of the attribute and find the matching input with data-LabelInp === that value.

how to get input array value by key with javascript function?

Here is sample code i try to create input array with key and on change i want to get the value of individual input array value.
<input type="text" name="items[1]" value="443" onchange="get_items(1)">
<input type="text" name="items[2]" value="233" onchange="get_items(2)">
<script>
function get_items(key)
{
alert($("items["+key+"]").val());
}
</script>
Simply pass this context as argument and get value.
<input type="text" name="items[1]" value="443" onchange="get_items(this)">
<input type="text" name="items[2]" value="233" onchange="get_items(this)">
<script>
function get_items(ele) {
alert(ele.value);
}
</script>
Refer fiddle
HTML:
<input type="text" name="items[1]" value="443" onchange="get_items(1)">
<input type="text" name="items[2]" value="233" onchange="get_items(2)">
JS:
function get_items(key)
{
alert($('input[name="items['+key+']"]').val());
}
You can get the event's target from event,
function get_items(e) {
console.log(e.target.value);
}
<input type="text" name="items[1]" value="443" onchange="get_items(event)">
<input type="text" name="items[2]" value="233" onchange="get_items(event)">
or, better, attach your listener in javascript:
function get_items(e) {
console.log(e.target.value);
};
var inputs = document.querySelectorAll("input");
for (var i = 0, el; i < inputs.length; i += 1) {
el = inputs[i]
el.addEventListener("change", get_items);
};
<input type="text" name="items[1]" value="443">
<input type="text" name="items[2]" value="233">
Here is some code that does what (I think) you are trying to do:
<input type="text" name="item1" value="443" onchange="javascript:get_items(1)">
<input type="text" name="item2" value="233" onchange="javascript:get_items(2)">
<script>
function get_items(key)
{
//alert($("items["+key+"]").val());
var input = $('input[name="item' + key + '"]');
var value = input.val();
alert(value);
}
</script>
jsfiddle: https://jsfiddle.net/9kvv2q7p/4/
You can use this
function get_items(key) {
alert($("input[name='items[" + key + "]']").val());
}
I hope I was helpfull
Your HTML is missing a closing quote for the name attributes.
The name attribute should not contain [ or ]
characters. Adding these characters will complicate matters.
You should hook up your event handlers in JavaScript, not HTML.
When practical, elements should have unique id attributes added to them, which will make accessing and identifying them much easier in JavaScript and CSS
Rather than trying to identify the textboxes with indexes, just gather them up and place them into an array or array-like container, where indexes will be automatically assigned to them.
Here is a working example of how to get values by index:
// This will scan the DOM and place all matched elements into a node list
// which is an array-like object
var textBoxes = document.querySelectorAll("input[type=text]");
// Or, you can get references to them individually:
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
// And, put them into an array on your own:
var ary = [txt1, txt2];
// No matter how you got your references to them, it's best to hook
// them up to event handler in JavaScript, not HTML
txt1.addEventListener("change", get_items2);
txt2.addEventListener("change", get_items2);
function get_items(key) {
// You can certainly pass a key to this function
// to identify which element you are talking about
alert(textBoxes[key].value);
}
function get_items2(evt) {
// But, event handlers are automatically passed
// a reference to the object that fired the event
alert(evt.target.value);
}
get_items(0); // Call the function to get first textbox value
get_items(1); // Call the function to get second textbox value
<input type="text" id="txt1" name="txt1" value="443">
<input type="text" id="txt2" name="txt2" value="233">

Show placeholder instead of the default value in html form

A text field in html form have a default value,
but I would like to show the placeholder instead of the default value.
any ideas?
From what you said here it sounds like you actually want to listen for the focus and blur events and just clear the contents of the <input> with some kind of cache to restore it if nothing gets typed.
<input id="foo" type="text" value="" data-value="" />
Then in script
var foo = document.getElementById('foo');
foo.addEventListener('focus', function () {
this.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
DEMO
Provided you are only concerned with browsers that support HTML5, the following is an option:
<input type="text" name="myText" placeholder="My Placeholder">
<input type="text" name="foo" placeholder="Foo Name"/>
<input type="hidden" name="foo" value="foo"/>
On one hand, it is doable; on the other hand, I'm not sure why you should.
$('input[type="text"]').each(function (i, o) {
var inputBox = $(o),
swapInValue = function () {
inputBox.val(inputBox.data('val'));
},
swapOutValue = function () {
inputBox.data('val', inputBox.val()).val('');
};
inputBox.blur(swapOutValue).focus(swapInValue);
});

How to get index of textfield array in the form by using Javascript? [duplicate]

This question already has answers here:
Get child node index
(13 answers)
Closed 9 years ago.
I have a form with dozen of textfield elements. Any change of their values shall execute Javascript function. And until now I know what I shall to do, but I can't detect index of textfield that triggered function. I tried some solution I saw here & there but wasn't successful.
<form action="" method="post" enctype="multipart/form-data" name="myforma1" target="_self" id="myforma1">
<input name="txtfield" type="text" id="txtfield" onchange="detect_it(this);" value="name of person" size="20" maxlength="25" />
<input name="txtfield" type="text" id="txtfield" onchange="detect_it(this);" value="name of person" size="20" maxlength="25" />
<input name="txtfield" type="text" id="txtfield" onchange="detect_it(this);" value="name of person" size="20" maxlength="25" />
...
<script>
function detect_it(oo)
{
alert('Index of triggered element is: ' + oo.index);
/* rest of code */
}
</script>
You probably shouldn't give all your inputs the same name and id.
However, you can still look for the parent node, then iterate over the parent's children until you found your node to retrieve its index.
Try this getIndex() function:
<script>
var getIndex = function (node) {
for (var i =0;i<node.parentNode.children.length;i++) {
if (node.parentNode.children[i] === node) {
return i;
}
}
}
function detect_it(oo) {
alert('Index of triggered element is: ' + getIndex(oo));
}
</script>
See this Fiddle: http://jsfiddle.net/LkJxV/
edit: corrected code (again) (thx #Felix)
Your problem here is that index is not a property of the element. It can have differnet indexes depending on context but you can try
Try something like:
function detect_it(oo){
var inputs = document.getElementsByTagName('input')
for (var i = 0 ; i<inputs.length ; i++){
if(oo == inputs[i]{
alert('Index of triggered element is: ' + i);
}
}
//enter code here
}

Categories