How to get previous DOM element in Javascript? [duplicate] - javascript

This question already has answers here:
Get next / previous element using JavaScript?
(10 answers)
Closed 6 years ago.
I'm using javascript to access previous element's attribute value.
My HTML :
<form>
<div>
<label for="name">Name :</label>
<input type="text" name="name">
</div>
<div>
<label for="email">E-Mail :</label>
<input type="email" name="email">
</div>
</form>
I use loop to read all input elements in my form.
But, i want to read the label's HTML.
ex.
Input Element : 'email'
Label : 'E-Mail'
Also i want Javascript Solution ONLY !
//////// I'm not using jQuery ! ///////

You can use .previousElementSibling property to get the label element.
var el = document.getElementsByTagName('input');
for(var i =0; i< el.length;i++){
console.log(el[i]);
console.log(el[i].previousElementSibling);
if(el[i].getAttribute("name")==el[i].previousElementSibling.getAttribute("for")){
console.log("it is label");
}
}
Here is the jsfiddle example.

Used the code here:Find html label associated with a given input
//associate all labels to inputs:
var labels = document.getElementsByTagName('LABEL'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor != '') { var elem = document.getElementsByName(labels[i].htmlFor)[0]; if (elem) elem.label = labels[i]; } }
//get email for example
email=document.getElementsByName("email")[0];
EmailLabelvalue=email.label.innerHTML;
It connects every label with its Input, than you can easily get it using input.label. To get its containing value use .innerHTML ...

Related

Selecting all textbox at once with javascript

In my work we have to fill a lot of textboxes to do some validations. After all, we need to erase all - one by one - to restart the process.
Has some way to erase all textbox content with javascript (the only one method we can use now)? A for loop maybe?
You should put all the input fields in a form and then reset the form by the .reset() method.
document.getElementById("reset").onclick= ()=>{
document.getElementById("form").reset()
}
<form id="form">
<input/>
<input/>
</form>
<button id="reset">Reset</button>
See an example on W3Schools or the docs on MDN
If you want to restore the fields to their initial value, reset the form as suggested by #dota2pro's answer.
OTOH, if you want to clear the elements regardless of their initial value, you can query the elements using a type (aka "tag") CSS selector via Document​.query​SelectorAll()
and iterate through the elements as below:
function go() {
let inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
}
<input type="text" value="a"><br>
<input type="text" value="b"><br>
<input type="text" value="c"><br>
<br>
<button onclick="go()">click to clear</button>
Note that:
document.querySelectorAll('input') fetches all <input>s regardless of their type attribute.
document.querySelectorAll('input[type="text"]') fetches all <input type="text">.
document.querySelectorAll('textarea') fetches all <textarea>.
If you want to combine, you can use the comma combinator:
document.querySelectorAll('input[type="text"],textarea')
You can get in different ways in javascript:
By ID : document.getElementById("id")
By class: document.getElementsByClassName("class")
By tag:
document.querySelectorAll("input")
or Jquery
By ID : $("#id")
By class: $(".class")
By tag: $("input")
Read documentation about that here
tru
[...document.querySelectorAll('input')].map(x=>x.value='')
var clean = () => [...document.querySelectorAll('input')].map(x=>x.value='');
<button onclick="clean()">Clear</button><br>
<input type="text" value="some"><br>
<input type="text" value="short"><br>
<input type="text" value="text"><br>
Bellow code will select all editable text-boxes
document.querySelectorAll('input[type="text"]:not(:disabled):not([readonly]))')
If you have JQuery available, you can do:
$('input[type="text"]').val('');
Or, if you prefer native:
for(var i = 0; i < document.getElementsByTagName('input').length; i++){
document.getElementsByTagName('input')[i].value = '';
}

How to enable a disabled input field? [duplicate]

This question already has answers here:
javascript remove "disabled" attribute from html input
(6 answers)
Closed 5 years ago.
I want to know how to enable a disabled input field.
<input type="text" class="form" value="Text" disabled="">
I've tried to use this code via tampermonkey
var fContrl = document.getElementsByClassName("form");
for (var i = 0; i < fContrl.length; i++)
fContrl[i].setAttribute("disabled", false);
But it doesn't work
You need to set the property not the attribute
// Disable
fContrl[i].disabled = true;
// Enable
fContrl[i].disabled = false;
remove the disabled attribute - see demo below:
var fContrl = document.getElementsByClassName("form");
for (var i = 0; i < fContrl.length; i++)
fContrl[i].removeAttribute("disabled");
<input type="text" class="form" value="Text" disabled="">
Try this way:
var fContrl = document.getElementsByClassName("form");
for (var i = 0; i < fContrl.length; i++)
fContrl[i].disabled=false;
Check this link.
You can directly remove the attribute disabled.
fContrl[i].removeAttribute("disabled");
Remove disable attribute from your input field.
JavaScript Code
fContrl[i].removeAttribute("disabled");
You can achieve it by changing the line
fContrl[i].setAttribute("disabled", false);
to
fContrl[i].disabled=false;

How do I use JavaScript to display one value in multiple places marked by elements with the same class? [duplicate]

This question already has answers here:
What is wrong with this getElementsByClassName call in Javascript? [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to show the same text value in designated elements marked by the same class. Basically, this text is a value that I am getting from a form input tag. I am trying to do this with JavaScript using a getElementById to gather the text value and then getElementsByClassName to replace the text value in specified places of a page. Please see the following code first in HTML:
collective noun: <input type="text" id="noun1" onkeypress="runGather()"><br>
something the <i class="collective_noun">collective noun</i> can make: <input type="text" id="noun2"><br>
adj describing <i class="collective_noun">collective noun</i>: <input type="text" id="adj"><br>
and then in the JS file:
function runGather() {
var noun1 = document.getElementById("noun1").value;
var collective_noun = document.getElementsByClassName("collective_noun").value;
for (var i = 0; i < noun1.length; i++) {
collective_noun[i].innerHTML = noun1;
}
}
You're setting collective_noun to just a value when you want to use the nodelist that's returned, and you're trying to loop through noun1, which is just the value of the node. Try this instead:
var i, l,
noun_1,
collective_nouns;
noun_1 = document.getElementById('noun_1').value;
collective_nouns = document.getElementsByClassName('collective_noun');
for (i = 0, l = collective_nouns.length; i < l; i += 1) {
collective_nouns[i].innerHtml = noun1;
}
Instead of using plain JavaScript, you could save yourself the headache and use jQuery. Here's a one-line example using jQuery:
$(".collective_noun").text( $("#noun1").val() );

Jquery Select all elements with data attribute common name [duplicate]

This question already has an answer here:
how do I find elements that contain a data-* attribute matching a prefix using jquery
(1 answer)
Closed 9 years ago.
I'm trying to use jQuery to select all the inputs in my form that have a data attribute with a similar name.
This is my form:
<form id = "myForm">
<input name="name" data-valid-presence=true >
<input name="age" data-valid-biggerThan="18" >
<input name="email[0]" data-valid-email=true >
<input name="email[1]" data-valid-email=true >
</form>
and my jQuery selector is:
var inputs = jQuery("#myForm").find("input[data-valid-email],[data-valid-length],[data-valid-presence], [data-valid-biggerThan]");
I'm looking for a way to select all the inputs that have a data-valid-* in them without having to find them one by one like this.
Any ideas?
You can use jQuery.filter:
var inputs = $('form').find('input').filter(function() {
var matched = false;
$.each(this.attributes, function(attr) {
if ( matched ) return;
matched = /^data-valid/.test(this.name);
});
return matched;
});

How to find which all check box is selected [duplicate]

This question already has answers here:
Javascript to check whether a checkbox is being checked or unchecked
(7 answers)
Closed 10 years ago.
I have a list of check box and i need to write a javascript function to find out which all the check boxes are clicked. can any one help?
<input type="checkbox" name="check_group[]" id="name" /> name
<input type="checkbox" name="check_group[]" id="age" /> age
<input type="checkbox" name="check_group[]" id="school" /> school
<input type="checkbox" name="check_group[]" id="company"> company
So if I click on only 2 I need to know which are the 2 I clicked on so that I can send for server side processing.
Given that the checkboxes all have the same name, you can use a function like:
function getChecked(name) {
var els = document.getElementsByName(name);
for (var i=0, iLen=els.length; i<iLen; i++) {
if (els[i].checked) {
// els[i] is checked, do stuff
}
}
}
Have a input type button and call this function on it's click
function callMeOnButtonClick()
{
var selectedBox = document.querySelectorAll('input[name*=check_group]');
// You may also use
// var selectedBox = document.getElementsByName('check_group[]');
// The above two statements will give you the same result. i.e., array of checkboxes having name check_group[]
var count++;
for(var i=0; i<selectedBox.length; i++)
{
if(selectedBox[i].checked)
{
count++;
// Do processing
}
}
alert("Number of selected checkbox: "+count);
}
you can use jQuery to find the checked elements in javascript
alert($("check_group[]:[checked=checked]").length);
and then you can use those values to send server side for processing

Categories