Get value from hidden field - JavaScript - javascript

I have a <input type="hidden" class="Key" value="1m2.123.mds.34g" />
How can I get the value without using jQuery?
With jQuery i just only write:
var parse = $('.Key').attr("value")
alert(parse);
I need this in pure JavaScript, maybe use RegEx? I will execute this script on txt file which will contain such line.

check this
window.onload=function(){
var hidden=document.getElementsByClassName("Key");
alert(hidden[0].value);
}
<input type="hidden" class="Key" value="1m2.123.mds.34g" />

var inputs = getElementsByClassName('Key');
for(var i=0; i<inputs.length;i++) {
console.log(inputs[i].value);
}

Easy! Just use getElementsByClassName. E.g:
document.getElementsByClassName('Key')[0].value
Or if you had to get the value by id you can use getElementById
document.getElementById('idHere').value

Here's 4 ways to get the value of .Key. Also I added a better way to do it in jQuery as well using the method val().
SNIPPET
var k = document.querySelector('.Key').value;
console.log(k);
// This works if .Key is inside a <form>
var e = document.forms[0].elements[0].value;
console.log(e);
var y = document.getElementsByTagName('input')[0].value;
console.log(y);
var s = document.getElementsByClassName('Key')[0].value;
console.log(s);
//BTW there's a better way of finding value with jQuery
var $Key = $('.Key').val();
console.log($Key);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1'>
<input type="hidden" class="Key" value="1m2.123.mds.34g" />
</form>

Thank you all. I resolve this problem as follow:
var regEx = /class="Name"+ value="(.*?)"/;
newName = result.match(regEx)[1];
var regEx2 = /class="Key"+ value="(.*?)"/;
var key = result.match(regEx2)[1];
Alert(key + ' ' + newName );

Related

Javascript output as value of hidden input

How can I set the ouput of this javascript function as the value for a hidden input on a html form?
document.write(states[i][1]);
works fine but I cannot get it to fill in the value with the code as shown below.
if (to == 'abbr'){
input = input.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
for(i = 0; i < states.length; i++){
if(states[i][0] == input){
document.getElementById("sid").value = (states[i][1]);
}
}
}
}
</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>
What is wrong with this code / what is the right way to do this?
Thanks!
This should do it.
HTML:
<input type="hidden" id="HiddenInput" />
JavaScript:
document.getElementById("HiddenInput").value = someFunction();
Have you checked if states[i][0] == input evaluates to true?
Write JavaScript code after html code end in your page or at the end of page.
I found a easier solution by just turning the entire function into a variable then the variable into the DOM:
var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');
document.getElementById("sid").value = response;
The following should work.
HTML:
<div style="display:none" id="example"></div>
Javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
element = document.getElementById('example');
element.appendChild(newtext);
}
function yourFunctionDataHere(){
return 'test1234';
}
addTextNode(yourFunctionDataHere());
Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.
Try it online on jsfiddle.

Dynamically assigning variable names JavaScript

I am trying to dynamically assign variable names using the user's input. For example:
var input = document.querySelector('input');
for(var i = 0; i < 10; i++){
var newVariableName = //input.value;
}
Any help would be very much appreciated.
Thank you,
Scratch Cat
Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:
Specify them the fixed way (e.g. obj.propertyName = 'Value')
Specify them using array notation (e.g. obj[propertyName] = 'Value'). In this case, note that propertyName is a string value.
In both cases, the result will be exactly the same. You could retrieve those properties likewise, e.g. obj.propertyName and obj[propertyName]. Both will return 'Value'.
In your case, #LuudJacobs's suggestion about using the window object will most probably do the trick...
You can use array in which the keys will be the input values and the value would be anything you want.
html
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
js
First you declare array
var a = new Array();
Then you use for loop to assign key names to array which will be the input values
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
Finally you can use those key names to access the values
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
Here is a link to an example
https://jsfiddle.net/309fpsjn/1/
<html>
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
<script>
var x = document.querySelectorAll(".example");
var a = new Array();
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
</script>
</html>

javascript concat() method adds newline randomly

I'm writing a JS code that reads the checkboxes in a particular , checks if they're selected, and if yes, appends their value to a string. This is the code that I have:
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
var str="";
for(var i =0; i< checkboxArr.length;i++){
var cb = checkboxArr[i];
if(cb.checked){
var newVal=cb.value;
str=str.concat(newVal);
str=str.concat(",");
}
}
alert(str);
The string that I get is:
value1
,value2
,value3
How are these newlines coming in the string ?
Also, the occurance of these newlines is random - sometimes they appear, sometimes I get the desired string.
I also tried combining the concat() calls into 1 statement, and I used the += operator as well, but no luck.
Any guidance is earnestly appreciated. Thanks
That's all you need. Use js right :D
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
var str = [];
checkboxArr.forEach(function(cb) {
if (cb.checked) str.push(cb.value);
});
alert(str.join(', '));
and if you still have the same result check your html code. It seems like you have line break right after your value in checkbox
check implementation with ES6, not sure why you are getting new line,
var btn = document.getElementById('btn');
btn.onclick = function(){
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]:checked');
var res = Array.from(checkboxArr).map(cb => cb.value.trim()).join(',')
console.log(res)
}
<div id="div_name">
<input type="checkbox" value="cb_1" />
<input type="checkbox" value="cb_2" />
<input type="checkbox" value="cb_3" />
<input type="checkbox" value="cb_4" />
<input type="checkbox" value="cb_5" />
</div>
<button id="btn">Check</button>

Get values of all textboxes with same name attributes in jquery

I need to get values of all textboxes with same name attributes using jquery.
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">
How can I get all values of textbox text[] and compare it using jquery.
I tried using
var values = $("input[name='text[]']")
.map(function(){return $(this).val();}).get();
but am no successful.
You can use map method and store the values into an array.
$(function(){
var values = $('input[name="text[]"]').map(function(){
return this.value
}).get()
})
http://jsfiddle.net/UugWW/
This one should work :
$('input[name="text[]"]');
You can loop on it to get all values.
$('input[name="text[]"]').each(function() {
alert($(this).val());
});
Let's split the requirement into smaller problems.
First you want to select all those inputs.
var $inputs = $("input[name='text[]']")
It returns a jQuery object, containing all the input named text[].
You also might not need to use square brackets into the name.
var inputs = $inputs.get();
Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.
var values = inputs.map(function takeValue(input) {
return input.value;
});
Use a selector like this:
$('input[type="text"][name="text[]"')
var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
textvalue= textvalue + document.getElementsByName("text").item(i).value;
}
alert(textvalue);

How to parse a variable in Javascript

I'm trying to use this code:
var field="myField";
vals[x]=document.myForm.field.value;
In the html code I have
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
But this gives me the error:
document.myForm.field is undefined
How can I get field to be treated as a variable rather than a field?
Assuming that your other syntax is correct (I havne't checked), this will do what you want:
var field="myField";
vals[x]=document.myForm[field].value;
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.
Use the elements[] collection
document.forms['myForm'].elements[field]
elements collection in DOM spec
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
var value = document.forms['myForm'].elements[field][index_of_field].value
eg.
var value = document.forms['myForm'].elements[field][0].value
and, if you want to get value of selected radio-button you have to check which one is selected
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
You have to do it like this:
var field = "myField";
vals[x] = document.myForm[field].value;
or even
vals[x] = document.forms.myForm.elements[field].value;
Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:
var vals = new Array();
$("form[name='myForm'] :radio").each(function() {
vals.push($(this).val());
});
:-D

Categories