Accessing hidden element value (javascript) - javascript

Pls have a look at the following code.
<script type='text/javascript'>
function apps(){
var app= new Array(8);
for (var i=0;i<8;i++)
{
app[i]= ....;
}
}
</script>
<input type="hidden" name="NEW" value= ? >
< ....button label="Submit" OnClick='apps();return false;'/>
Here the apps() method gets executed on clicking the Submit button.
I want to access the value of app (Array) by use of a hidden element. Pls let me know what code I should write for this purpose.

<input type="hidden" name="foo" value="bar" />
document.write(document.getElementsByName('foo')[0].value);
output is "bar". getElementsByName returns an array of matching form elements with the name supplied. the [0] grabs the first match, and .value retrieves the value.

You can do this with JQuery as well.
<input id="foo-hidden" type="hidden" name="foo" value="bar" />
<script type="text/javascript">
function apps() {
var app= new Array(8);
for (var i=0; i < 8; i++) {
app[i]= $('#foo-hidden').val();
}
}
</script>

Related

Get form values through JavaScript

This is my HJTML code. I don't know how to get values stored in filtertime[] using JavaScript and make them show on my screen.
<form action="index.php" method="post" >
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Morning"></div> <div class="f-txt-r">Morning</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Afternoon"></div> <div class="f-txt-r">Afternoon</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Evening"></div> <div class="f-txt-r">Evening</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Night"></div> <div class="f-txt-r">Night</div></div>
<div class="col-lg-12"><input type="submit" name="button" class="apply-filter" value="Apply Filter"></div>
</form>
<script>
var new = document.getElementsById("test").innerhtml
</script>
How can I get input values in JavaScript through value is stored in array as filtertime[]?
try
in your form
<form action="index.php" id="myform" method="post" >
in jQuery
var datastring = $("#myform").serialize();
By JS
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
Add id in your form tag.
<form action="index.php" id="form_name" method="post" >
Use below code to get all form element by JS :-
document.forms["form_name"].getElementsByTagName("input");
Note:- Above Code will work only if you don't have selects or textareas in your form.
If you have assigned id in DOM element like below,
<input type="text" name="name" id="uniqueID" value="value" />
Then you can access it via below code:-
Javascript:-
var nameValue = document.getElementById("uniqueID").value;
If you have Radio button in your form, then use below code:-
<input type="radio" name="radio_name" value="1" > 1
<input type="radio" name="radio_name" value="0" > 0<br>
Javascript:-
var radios = document.getElementsByName('radio_name');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Hope it will help you :)
this is the easiest way to get array of your form items
var arrValues = [];
for (var x =0; x < document.getElementsByClassName("morning").length ; x++)
{
arrValues.push(document.getElementsByClassName("morning")[x].checked);
}
To do that, the easiest way is to select all input with the "morning" class and after, foreach look if is checked :
var item = document.getElementsByClassName("morning"); // get all checkbox
var checkboxesChecked = []; // result array with ckecked ckeckbox
for (var i=0; i<item.length; i++) {
// if is checked add the value into the array
if (item[i].checked) {
checkboxesChecked.push(item[i].value);
}
}
console.log(checkboxesChecked);
In the "checkboxesChecked" array you have all the values of the checked box.

Javascript when checkbox is checked, add checkbox ID to an array

I am defining an array of checked checkboxes:
<script>
var all_checked = new Array();
function add_checked(checked_checkbox_id)
{
all_checked.push(checked_checkbox_id);
}
<html>
<input type="checkbox" name="a" id="1" value="1" onclick="add_checked(?????);" />
</html>
So my question is how to pass the checked checkbox ID to the function to append to the global
all_checked
variable
Pass this in your function and then use it to get the id property:
HTML
<input type="checkbox" name="a" id="1" value="1" onclick="add_checked(this);" />
JavaScript
var all_checked = new Array();
function add_checked(el) {
all_checked.push(el.id);
}
Remember, this will push the id to the array no matter what, whether the box is checked or unchecked, even if the id already exists in the array.
JSFiddle
Use this keyword by passing to yout function.
onclick="add_checked(this)";
Here you can the id as
this.id
then in
function add_checked(checked_checkbox) {
all_checked.push(checked_checkbox.id);
}
FYI: script tag should be within html tag
HTML:
<button onclick="send_query(document.getElementsByTagName('input'))">
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}

Javascript foreach input in form for Name and Value

I am just practicing some javascript and i used to use JQuery a lot! I have had no major experience with raw javascript and i want to learn it just as i did JQuery. I have a simple form and a javascript function to go with it onsubmit and i want to get the name and value of each input in the form with my function but it doesnt seem to work can someone help me out?
<!DOCTYPE html>
<html>
<head>
<title>Foreach Practice</title>
<script type="text/javascript">
function Get() {
var Form = document.getElementById('Form');
for(I = 0; I < Form.length; I++) {
var Value = this.attribute('name').value;
alert(Value);
}
}
</script>
</head>
<body>
<form id="Form" onsubmit="return false;">
<input type="text" name="User" placeholder="Username" />
<input type="password" name="User" placeholder="Password" />
<input type="submit" name="Submit" onclick="javascript:Get();" />
</form>
</body>
</html>
This question is probably better suited to code review, but whatever.
> function Get() {
Variable names starting with a capital letter are, by convention, reserved for constructors. Also, names should indicate what the function does, a generic "get" function doesn't give much of a hint. A better name might be getFormValues.
> var Form = document.getElementById('Form');
There is a document.forms collection available that can be used as an alternative to calling a method:
var form = document.forms('Form');
> for(I = 0; I < Form.length; I++) {
You should always declare variables in an appropriate scope (noting that ECMAScript only has global, function and eval scope, there is no block scope), especially counters. Also, the form's length attribute is the number of controls in the form. Since it's a live collection, getting the length every time when you don't need to is potentially a performance hit, so cache the value:
for (var i = 0, iLen = form.length; i < iLen; i++) {
> var Value = this.attribute('name').value;
The value of this is set by how you call a function. If the function is called by a handler, then depending on the browser and method attachment, this will reference the element whose listener called the function. In this case, because the function is called by an inline listener, this has not been set so will default to the global object.
You can easily pass a reference to the element from the listener if you do:
<input ... onclick="getFormValues(this);" ... >
Now your function will receive a reference to the element and can conveniently get a reference to the form and iterate over the controls. Finally, it is rare to need to access a form control's attribute values, you nearly always want to access properties. So here's the re-written function:
function getFormValues(element) {
var form = element.form;
var controls = form.controls;
for (var i=0, iLen=controls.length; i<iLen; i++) {
alert(controls[i].name + ': ' + controls[i].value);
}
// Prevent form submission
return false;
}
Lastly, you are better to call the listener from the form rather than the submit button, since forms can be submitted by means other than clicking a submit button. Oh, and don't call any form control "submit" or use any name that is the same as a form method as it will overwrite the same–named method. You get away with it here due to capitalisation, but that is not much defense.
The related HTML can be (note that the form now doesn't need either a name or id):
<form onsubmit="return getFormValues();">
<input type="text" name="userName" placeholder="Username">
<input type="password" name="userPassword" placeholder="Password">
<input type="submit" name="submitButton">
</form>
You should iterate to form's children and use getAttribute function to get attribute value.
Try this:
function Get() {
var Form = document.getElementById('Form');
var childs = Form.children;
for(I = 0; I < childs.length; I++) {
var Value = childs[I].getAttribute('name');
alert(Value);
}
}
Anyone looking for the answer to this i figured it ou just by using random attempts of rearranging my code but here it is.
<!DOCTYPE html>
<html>
<head>
<title>Foreach Tutorial</title>
<script type="text/javascript">
function Get() {
var Form = document.getElementById('Form');
for(I = 0; I < Form.length; I++) {
var Name = Form[I].getAttribute('name');
var Value = Form[I].value;
alert(Name + ' : ' + Value);
}
}
</script>
</head>
<body>
<form id="Form" onsubmit="return false;">
<input type="text" name="User" placeholder="Username" />
<input type="password" name="Pass" placeholder="Password" />
<input type="submit" name="Submit" onclick="Get();" />
</form>
</body>
</html>

How to retrieve the value from a radio button in javascript?

Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.
This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference
Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
​function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
​
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.
function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/
You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".

Error document.form is undefined in javascript

I have a code javascript:
<form onsubmit="return false;" action="">
<input type="radio" name="type" id="type0" value="0" onclick="toggleSet(this)" checked />type 0
<input type="radio" name="type" id="type1" value="1" onclick="toggleSet(this)" />Type 1
</form>
<script>
function toggleSet() {
for(var i=0; i<document.form.type.length; i++) {
if(document.form.type[i].checked) {
var type = document.form.type[i].value;
}
}
alert(type);
}
</script>
ouput error: document.form is undefined, how to fix it ?
The form property of document does not exist. You're probably confused with the document.forms HTML collection:
document.forms[0]; //First <form> element
document.forms['name_of_form']; //Points to <form name="name_of_form">
Fixed code:
function toggleSet() {
var form = document.forms[0];
var type; //Declare variable here, to prevent a ReferenceError at the end
for(var i=0; i<form.type.length; i++) {
if(form.type[i].checked) {
type = form.type[i].value;
break; // After finding an occurrence, break the loop:
// You expect only one value
}
}
alert(type);
}
Just define the name parameter in the form tag like < form name="form1" ...> and call it through array value as below.
e.g var type = document.form1.type[i].value;
There is no property document.form.
document has a property forms which is an array of the forms the document contains. You access the desired form this way:
document.forms[0] // first form
document.forms['theForm'] // form with name="theForm"
document.form is not standard as far as I know. document.forms (note the 's') is. Documents can have multiple forms.

Categories

Resources