Javascript select all HTML input fields with array style name - javascript

I have a form that I am building and would like to have a javascript to select and manipulate all of the fields that are within the named array:
<input type="text" name="location[street]" value required />
<input type="text" name="location[city]" value required />
<input type="text" name="location[zip]" value required />
<input type="text" name="location[state]" value required />
How can I build a selector for javascript to toggle all of the elements disabled state?
Jquery is possible but not preferred. I would prefer a method that would work without libraries - such as document.getElementsByName().

I believe that querySelectorAll doesn't have support for a selector to get an element by an attribute, like jQuery would be input[name^="location"](docs). So, try this:
var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].name.indexOf("location") > -1)
{
els[i].disabled = true;
}
}
Fiddle. I will be glad to hear that I'm wrong and there is a way for doing this only using a selector.
Anyway, you can use the fieldset and make your code more semantic by disabling only the fieldset, if you like: Fiddle.
UPDATE
In order to disable all textarea and select elements as well, just include those tags on the selector:
var els = document.querySelectorAll('input, textarea, select');
Fiddle

Alternative to queryselector would be getElementsByTagName
var i;
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; ++i) {
var name = inputs[i].getAttribute("name");
if(name.indexOf("location") > -1)
{
inputs[i].disabled = true;
console.log(name);
}
}
link to JSFIddle

Related

JavaScript changing value of custom attribute by searching another custom attribute

thanks for reading.
So the input tags don't have an ID or a class name.
The value attribute is also custom.
This is what I was trying.
HTML
<input name="password" data-value="">
.
#"var aTags = document.getElementsByTagName('input');
var searchText = 'password';var found;
for (var i = 0; i < aTags.length; i++)
{
if (aTags[i].textContent == searchText){found =
aTags[i].setAttribute('data-value','123456789');
alert(found.getAttribute('data-value')); break;}
}");
or
var myInput=$('input[data-value='']').setAttribute('data-value','12345678');
alert(myInput.getAttribute('data-value'));
I tried using get elements by name, but there is nothing showing. As I think there may be multiple results. And I want a safer solution.
well thanks everyone, I didn't expect such a great response.
I was interested to see how this would be solved, but apparently the following line works
aTags[i].value='123456789';
I suppose anything with the word value is seen as a value field if the exact 'value' attribute can't be found.
Thanks flash, attr might work for this also I suppose.
var myInput = $('input[name="password"]').setAttribute('data-value','12345678');
alert(myInput.getAttribute('data-value'));
Try this
Since you are using jQuery already you can use the attr() method to get the value of the specified attribute.
var myInput = $('input[data-value]').attr("data-value","12345678");
console.log(myInput.attr('data-value'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-value="">
var myInput = $('input[name="password"]').attr('data-value','12345678');
alert(myInput.attr('data-value'));
Try something like this
I hope it will help.
const setAttribute = (attr, val) => input => {
return input.setAttribute(attr, val)
}
window.addEventListener("load", () => {
const searchValue = "1231"
const selector = `input[value='${searchValue}']`;
const inputs = Array.from(document.querySelectorAll(selector));
inputs.map(setAttribute("data-value", "1231231"))
})
<input value="1231" />
<input value="1231" />
<input value="aaa" />
with jQuery you can access the data attributes directly, but you must cycle through them as there may be more than one:
$.each($('input[data-value='']'),function(){
$(this).data('value','12345678');
});
or, if the input field is just one, use an id:
<input type='password' id="pwd" data-value="" />
and
$('#pwd').data('value','12346578');
<input /> is a self closed element so it will not have textContent attribute. But, yes, in some browsers it will work if you type <input>text content</input>, but in others it won't work.
What i recommend is to keep that value in an attribute right on the input. Follow the example bellow.
Documentation:
About textContent: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
Self Closing elements: https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
<input type="text" data-textcontent="password"/>
JS
var aTags = document.getElementsByTagName('input');
var found;
var searchText = 'password';var found;
for (var i = 0; i < aTags.length; i++)
{
console.log(aTags[i].getAttribute('data-textcontent'));
if (aTags[i].getAttribute('data-textcontent') == searchText){
aTags[i].setAttribute('data-value','123456789');
found = aTags[i].getAttribute('data-value');
break;
}
}
console.log(found);

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

How to get the innerHTML of an input control including the values?

I have a div, its called tab1. Inside the tab1 div are many inputs (fields and radio buttons). I am getting the innerHTML like this:
document.getElementById("tab1").innerHTML;
Example code:
<div id="tab1">
<input type="text" id="text1" />
</div>
That works, but if I entered any value into a text1 input for example, its not in the innerHTML. How would I get the innerHTML including the entered values? Is that possible at all?
Thanks!
<div id="tab1">
<input type="text" id="text1"
onkeyup="javascript:this.setAttribute("value", this.value);"/>
</div>
This will gives the values with div's innerHTML.
document.getElementById("tab1").innerHTML;
You can change the event accordingly, I set it onKeyUp.
If you want to get the values of inputs/radios, you can do it with jQuery:
var Inputs = $("div#tab1 input, div#tab1 radio");
You now have an array of all input and radios in the variable Inputs. You can then access the values like this: Inputs[0].value
If you want to use plain JavaScript that could look like this:
var Inputs = document.getElementById("tab1").getElementsByTagName('input');
You can now access them like:Inputs[0].valueandRadios[0].value`
#edit
Thanks, I corrected these mistakes.
If you type something in the textbox, what does the innerHTML look like? Does it look like
<input type="text" id="text1" value="your_value" />?
If so, here is a simple function that returns what you want:
function getInnerHtml() {
var div = document.getElementById("tab1");
var childNodes = div.childNodes;
var innerHtml = "";
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (node.nodeType == 1) {
if (node.getAttribute("type") == "text") {
if (node.value != "") {
//! This will change the original outerHTML of the textbox
//If you don't want to change it, you can get outerHTML first, and replace it with "value='your_value'"
node.setAttribute("value", node.value);
}
innerHtml += node.outerHTML;
} else if (node.getAttribute("type") == "radio") {
innerHtml += node.outerHTML;
}
}
}
}
Hope it's helpful.

Javascript Code inside input value

I use Maxminds GEOIP tool and just call this after the body:
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
To print out the City and State I just paste this into the HTML doc:
<script>document.write(geoip_city());</script>
<script>document.write(geoip_region());</script>
I want to pass those values in hidden inputs that I can submit and assign to variables. What I want is this, but obviously the syntax is way off:
<input type="hidden" name="city" value="<script>document.write(geoip_city());</script>" />
I've tried searching for it here but couldn't find an answer, can anybody help? Thanks!
I would write this (using jQuery) as:
var geo_city = geoip_city();
var geo_region = geoip_region();
$(document).ready(function(){
$("#city").val(geo_city);
});
<input type="hidden" id="city" name="city" value="" />
This code will take the variable geo_city and put it in your hidden text field that has the ID city.
I'd suggest adding a class to the elements you want populated by the geoip service, such as the obvious geoip class-name, and using a map of the geoip functions to populate the values of the hidden input elements based on their name, such as (untested, and, without a public API, untestable unfortunately):
var geoipMap {
'city' : geoip_city(),
'region' : geoip_region(),
'country' : geoip_country() // and so on...
};
var inputs = document.getElementsByTagName('input'),
geoipInputs = [];
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].className.indexOf('geoip') !== -1) {
geoipInputs.push(inputs[i]);
}
}
for (var i = 0, len = geoipInputs; i < len; i++) {
geoipInputs[i].value = geoipMap[geoipInputs[i].name];
}

Javascript form validation

I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.
What I'm trying to accomplish is to check only the ones that have the class name as "required"
<input name="a1" class="required" type="text" />
<input name="a2" class="" type="text" />
<input name="a3" class="required" type="text" />
Thanks
I'm not at all against the libraries suggested by others, but I thought that you may want some samples of how you could do it on your own, I hope it helps.
This should work:
function validate() {
var inputs = document.getElementsByTagName("input");
for (inputName in inputs) {
if (inputs[inputName].className == 'required' && inputs[inputName].value.length == 0) {
inputs[inputName].focus();
return false;
}
}
return true;
}
Also lets say your inputs are in a form named "theForm":
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
if (theForm.elements[i].className == "required" && theForm.elements[i].value.length == 0) {
theForm.elements[i].focus();
return false;
}
}
return true;
}
Of course you would trim the value and/or add the appropriate validation logic for the application, but I'm sure you can get the idea from the sample.
You can also store arbitrary data on the input itself and read it using the getAttribute() method on the element. For example you could have this element in your html (regex requires a 3 digit number):
<input name="a1" validate="true" regex="[0-9]{3}" type="text" />
you could use this method to run the regex in the validation routine.
function validate() {
for (var i = 0; i < theForm.elements.length; i++) {
var elem = theForm.elements[i];
if (elem.getAttribute("validate") == "true") {
if (!elem.value.match(elem.getAttribute("regex"))) {
elem.select();
return false;
}
}
}
return true;
}
Hope this helps.
I use the jQuery validation plugin. Works really well and fits your stated desire to only need class attributes.
$(document).ready( function() {
$('form').validate();
});
Is all it takes to set up the validation once you have your required fields marked.
I would recommend you to use this javascript based css selector wich will get all elements of a specific class. Validating the form just like the way you mentioned.
A pattern for this that I have been using for a long time and has served me well is wrapping the control with a DIV, or P and marking that as required.
<div class="form-text required">
<label for="fieldId">Your name</label>
<input type="text" name="fieldName" id="fieldId" value="" />
</div>
This means that I can pick out the required fields to validate easily with a CSS selector.
.required input, .required select
In jQuery, you can test input with something like this:
$('form').submit(function(){
var fields = $(this).find('input, textarea, select'); // get all controls
fields.removeClass('invalid'); // remove
var inv = $(this).find('input[value=""], select[value=""]'); // select controls that have no value
if (inv.length > 0) {
inv.addClass('invalid'); // tag wrapper
return false; // stop form from submitting
}
// else we may submit
});
In plain Javascript it would be more than I care to type out, but along the lines of:
var badfields = [];
var fields = theForm.getElementsByTagName('input');
for (var i=0; i< fields.length; i++ ) {
if ( fields[i] && fields[i].parentNode && fields.value == '' &&
/(^| )required( |$)/.test( fields[i].parentNode.className ) ) {
badfields.push( fields[i] );
}
}
// badfields.length > 0 == form is invalid
The most immediate benefit of wrapping the label and input (and optionally: hint text, error...) as a control "set" in this way is that you can apply CSS styles on the input and label together.
.required input, .required select {
border : 1px solid red;
}
.required label {
color : #800;
}
.invalid input, .invalid select {
background-color : #f88;
}
I recommend using a ready made solution for your form validation as things can quickly add on: How will you validate checkboxes? Can checkboxes be required? (EULA?) What about radio buttons, how will you check those?
Most validation solutions will also provide sugar such as verifying correct data (say, email addresses) rather than just checking if it's there.
I'm a little surprised that no one mentioned YUI.
You can easily use getElementsByClassName method of Dom class in the following manner:
var aElements = YAHOO.util.Dom.getElementsByClassName('required', 'input');
for (var i = 0; i < aElements.length; i++)
{
// Validate
}
More method information is available here and more general info is here

Categories

Resources