JavaScript changing value of custom attribute by searching another custom attribute - javascript

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

Related

Undefined Input Value When Checking ByClassName

I am trying to find the value of an input by className using pure JavaScript. When I run similar code for and ID it works, but when I try with a class name it returns undefined. I am able to do this with jQuery but I want to achieve it with pure JavaScript to have a better understanding of the language. Thank you!
JAVASCRIPT
var input1 = document.getElementsByClassName("blank1");
var submit = document.getElementsByClassName("submit");
correctAnswer = 'hello';
submit[0].addEventListener('click', checkFillIn);
function checkFillIn(){
if ( input1[0].value === correctAnswer ){
console.log('correct!');
}else{
console.log('incorrect');
}
}
HTML
<p><input id="blank1" value="" type="text"></input></p>
Submit
Please add class attribute on your input element. See example below:
<input id="blank1" class="blank1" value="" type="text">
Of course, you wouldn't want to make the id same with the class attribute.
Ot returns undefined because you have an error in your syntax:
getElementsByClassName(blank1)
blank1 was the ID not the class
This should work:
var input1 = document.getElementById("blank1");
var submit = document.getElementsByClassName("submit");
correctAnswer = 'hello';
// submit is an array getElementsByClassName returns an array of elements
submit[0].addEventListener('click', checkFillIn);
function checkFillIn(){
if ( input1.value === correctAnswer ){
console.log('correct!');
}else{
console.log('incorrect');
}
}
<p><input id="blank1" value="" type="text"></input></p>
Submit
The error in your code is on line 1, where you get the first Element in javascript. It should be:
var input1 = document.getElementById("blank1");
This is because blank1 is an ID, not a class name.
Hope this helps!
you need to change var input1 = document.getElementsByClassName("blank1");to var input1 = document.getElementsById("blank1");or add class="blank1"to your input .

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!

Javascript select all HTML input fields with array style name

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

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.

Grabbing User Input

First name: <input type="text" name="firstname"></input>
<input type="submit" value="Submit" />
Let's say I have the simple form above. How would I grab what the user inputted in the First Name field in JS. I tried:
document.getElementsByTagName("input")[1].onclick = function() {
inputted = document.getElementsByTagName("input")[0].innerHTML;
}
But that doesn't work. How would I do this?
Use value for text inputs:
inputted = document.getElementsByTagName("input")[0].value;
Also make sure to add var keyword to your variables so that you don't create a global variable:
var inputted = document.getElementsByTagName("input")[0].value;
You should also not put closing </input> tag since it is self-closing tag:
<input type="text" name="firstname" />
By the way you can also get elements value using below syntax:
formName.elementName.value;
Or
document.forms['formName'].elementName.value;
In your case it would be:
var inputted = formName.firstname.value;
Or
var inputted = document.forms['formName'].firstname.value;
Replace formName with whatever name is of your <form> element.
Lastly you can also get element's value if you apply id to it:
<input type="text" name="firstname" id="firstname" />
and then use getElementById:
var inputted = document.getElementById('firstname');
var inputs=document.getElementsByTagName("input"),
i=inputs.length;
//
while(i--){
inputs[i].onclick=myClickEventHandler;
};
//
function myClickEventHandler(evt){
var myVal;
switch (this.name) {
case 'firstname':
myVal = this.value;
break;
};
};
If you are using a form, you could try something like this instead :
var input = document.forms["formName"]["fieldName"].value;
Else, make use of the .value attribute :
var input = document.getElementsByTagName("input")[0].value;

Categories

Resources