Get form values through JavaScript - 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.

Related

How to push values to input type hidden when clicked on radio button using jQuery?

I am getting values from one variable in array format so by using for loop it will iterate and when click on input type radio button each value with comma separated push to hidden field
I tried this but nothing gets inserted. How can I push those values to the hidden field?
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").push(id[i]); //values like 1,2 want to push in hidden field when click on radio button
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="" />
<input type="radio" name="radion_btn2" value="" />
As per your code. for(var i = 0; i < id.length; i++) { run two times and whenever your event occur. At that time i value come 2 and id[2] comes undefined. Below code should work.
var id = ["1", "2"]; // getting this value from another varaible in array format
arrayData = [];
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
console.log($(this).val());
arrayData.push($(this).val()); //values like 1,2 want to push in hidden field when click on radio button
$('.selected_val').val(arrayData.join());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="1" />
<input type="radio" name="radion_btn2" value="2" />
You can simulate a push by adding the hidden input's value before the new value
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$(".selected_val").val("");
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").val((i == 0 ? "" : ",") + $(".selected_val").val() + id[i]);
});
}
Here's an example of one approach that might help. See comments in snippet below.
let obj = {}; // create an empty object to store the clicked values
$(".radio").change(function() { // when a radio button is clicked
obj[this.id] = $(this).val(); // store it in the object
$(".selected_val").val(JSON.stringify(obj)); // and add the object to hidden field as string
console.log($(".selected_val").val()); // spit it out to the console
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" class="radio" name="radion_btn1" id="1" value="1" />1
<input type="radio" class="radio" name="radion_btn2" id="2" value="2" />2
<input type="radio" class="radio" name="radion_btn3" id="3" value="3" />3
You'll notice I added a common class for all radio buttons. This is what I'm attaching the event handler to. I also added the IDs to the radio button elements as well.
This may or may not work best for your scenario, but hopefully gets you started in the right direction.
Update
If you'd rather store the values in an array, just change it to an array:
let arr = [];
$(".radio").change(function() {
arr.push($(this).val());
$(".selected_val").val(JSON.stringify(arr));
}
Of course, that won't associate the ID with the value like with an object.

How to get the selected radio buttons value?

i am trying to get the value of selected radio buttons so i can submit my form using Ajax i searched here for some help but i couldn't find any useful solution
<input type="radio" id="answer" name="answer<?php echo $function::escape_string($question_row->question_id); ?>"
value="<?php echo $function::escape_string($answer_row>answer_id); ?>"/>
-HTML Output
<input type="radio" id="answer" name="answer16" value="107"/>
<input type="radio" id="answer" name="answer17" value="109"/>
<input type="radio" id="answer" name="answer15" value="104"/>
i found this function here
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert("Size is " + sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
var radioinputs = findSelection("answer");
But I do not know what to change so I can make it work with me properly
You can structure like this:
function findSelection(field) {
var test = document.getElementsByClassName(field);
var sizes = test.length;
//alert("Size is " + sizes);
result = [];
// result[16]=107;
// result[17]=109;
// result[15]=104;
for (i=0; i < sizes; i++) {
var index = test[i].dataset.index;
if(test[i].checked == true){
result[index] = test[i].value;
}else{
result[index] = undefined; // for a answer doesn't have a value
}
}
return result;
}
function checkfunction(){
var radioinputs = findSelection("radioanswer");
console.log(radioinputs);
console.log(radioinputs[15]);
};
<form id="form1">
<input type="radio" class="radioanswer" name="answer16" data-index="16" value="107"/>
<input type="radio" class="radioanswer" name="answer17" data-index="17" value="109"/>
<input type="radio" class="radioanswer" name="answer15" data-index="15" value="104"/>
<button type="button" onclick="checkfunction();"> Check </button>
</form>
A class can has multiple instances, but id has only one! And you can see document about data attributes here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
From the looks of it you have a dynamic name field, i.e. name="answer2", name="answer3", etc. Because of that your query document.getElementByName(field) will not find a field matching "answer".
To remedy this either get rid of the dynamic name or if you really need it then I would say add a class to all those radio buttons and use document.getElemenetsByClassName.

Dynamic assigning of event listener for multiple classes is not working

Im struggling to find problem.
Idea behind code:
dynamically assign event listener "oninput" to specific inputs on page determined by classes stored in "classes" array.
Problem:
function PassValue does not handle any element event where class is different from the last index in "classes" array(only the last class in array is handled).
When I change order of "class" array elements it results in different class being handled - again class on last index in array.
Image of how it works (or check Snippet)
When I hover over console element in first part "Datum" should be highlighed just as "Blast KD" is on second part. Its simplified representation of when I Type something in them, same text should appear in input under them, but that works only for one of them.
Question:
Does anyone know why is it happening and how to fix it(so all inputs are handled)?
$(function() {
$('.constant-select-form-numeric').attr('list', 'consoptions-numeric');
$('.constant-select-form-numeric-NT').attr('list', 'consoptions-numeric-NT');
$('.constant-select-form-date').attr('list', 'consoptions-date');
});
$(document).ready(function() {
var classes = ['.constant-select-form-date', '.constant-select-form-numeric', '.constant-select-form-numeric-NT'];
var form = $(document).find('form');
for (var j = 0; j < classes.length; j++) {
var c = classes[j];
//console.log(c);
var e = $(document).find(c);
if (e.length > 0) {
// ... switch(c) differentiating classes from each other(assingning atributes)
switch (c) {
case '.constant-select-form-date':
form[0].innerHTML += "<datalist id='consoptions-date'>\n\
<option data-value='-1'>Unknown</option>\n\
</datalist>";
break;
case '.constant-select-form-numeric-NT':
form[0].innerHTML += "<datalist id='consoptions-numeric-NT'>\n\
<option data-value='-2'>NT</option>\n\
</datalist>";
break;
default:
form[0].innerHTML += "<datalist id='consoptions-numeric'>\n\
<option data-value='-3'>NA</option>\n\
</datalist>";
break;
}
// assign EventListener to each element of c
for (var i = 0; i < e.length; i++) {
var element = $("input[for=" + e[i].attributes.for.value + "]")[0];
var hidden = $("input[name=" + e[i].attributes.for.value + "]")[0];
element.value = hidden.value;
element.addEventListener("input", function(elem) {
PassValue(elem.target);
});
PassValue(element);
//print element DOM
console.log(element);
}
}
}
});
function PassValue(element) {
console.log(element);
var x = element.value;
console.log(x);
// rest of function...
var hiddenInput = $(document).find("input[name=" + element.attributes.for.value + "]")[0];
hiddenInput.value = x;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body>
<form>
<fieldset class="form-group">
<label for="datum">Datum: </label>
<input for=datum class="form-control constant-select-form-date">
<input type="text" name="datum" id="frm-newMessageForm-datum">
</fieldset>
<fieldset class="form-group">
<label for="datum1">Datum1: </label>
<input for=datum1 class="form-control constant-select-form-date">
<input type="text" name="datum1" id="frm-newMessageForm-datum1">
</fieldset>
<fieldset class="form-group">
<label for="blast_kd">Text: </label>
<input for=blast_kd class="form-control constant-select-form-numeric">
<input type="text" name="blast_kd" id="frm-newMessageForm-blast_kd">
</fieldset>
<fieldset class="form-group">
<label for="blast_kd1">Text1: </label>
<input for=blast_kd1 class="form-control constant-select-form-numeric">
<input type="text" name="blast_kd1" id="frm-newMessageForm-blast_kd1">
</fieldset>
</form>
</body>
</html>
Nevermind, I solved it with completely different approach on different layer.(adding db constant fields is supposed to be in different layer, not in js)

Loop radio-button form javascript

I am trying to loop a radio-button form but with no success.
Despite the length of the form is 3 (same as number of radiobuttons) I can not access individual elements.
The purpose is to change the text. Its works If I want to access the first element:
var child = form.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
this returns the first radiobutton text.
But if I create a loop out of this
function getRadioBInfo() {
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var iForm = form[i];
var child = iForm.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
}
}
.. I get I TypeError: child is null
What is wrong with this code?
HTML
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
I think you are looking for something like following.
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var child = form.getElementsByTagName('input')[i];
alert(child.nextSibling.nextSibling.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
Since you've tagged jquery, you could use:
$('[name=delivering']).each( function() {
alert( $(this).find('label').html() );
});
To get the label followed after the radio button you could try this:
function getRadioBInfo() {
var form = document.getElementById("myform");
var radios = form.querySelectorAll('input[type=radio]');
var i;
for (i = 0; i < radios.length; i++) {
var radio = radios[i];
console.log(radio.nextSibling.innerHTML);
}
}
getRadioBInfo();
pitfall: there shouldn't be whitespace between the radio or the button. Otherwise nextSibling returns text and not the label
demo
Why you are not getting by name
Try this
function getRadioBInfo() {
var arrRadioBtns = document.getElementsByName("delivering");
for (var i = 0; i < arrRadioBtns.length; i++) {
var btn = arrRadioBtns[i];
alert (btn.value);
}
}
Working Example
form[i] contains only radio buttons.If You want to take the labels Try using
var lbl = document.getElementsByTagName('label');
for (var i=0;i < lbl.length; i++){ lbl[i].innerHTML = 'radio' + i; }
and loop through the labels and change the text
Couple of observation
var form = document.getElementById("myform");
form will not be an array,Instead it will be a String,So you are iteration of the string.length;
You can use doucment.getElementsByName to get all radio buttons with common name
Hope this snippet will be useful
function getRadioBInfo() {
//Retun collection of radio button with same name
var _getRadio = document.getElementsByName("delivering");
// loop through the collection
for(var i = 0;i<_getRadio.length;i++){
//nextElementSibling will return label tag next to each radio input
console.log(_getRadio[i].nextElementSibling.innerHTML)
}
}
getRadioBInfo();
Jsfiddle

Display value of checked check boxes javascript

Here I have written a javascript which selects all checkboxes on checking one checkbox and I want to display all the checked checkboxes value on button click. here it does selectall function correctly(ie. it selects all checkboxes). I am new to javascript and I need some help to display all the checked check box values, can any any one provide me the code to select all checkbox by clicking on a check box and display values of only selected checkboxes in a single function using javascript only...
Here is the javascript code
<script>
var checked=false;
function checkedAll ()
{
var c = document.getElementsByName("viju");
checked = document.getElementById('causelist_month').checked;
for (var i =0; i < c.length; i++)
{
c[i].checked=checked;
}
}
</script>
Here the HTML code
<input type="checkbox" name="causelist_month" id="causelist_month" onclick="checkedAll ();">select all/unselect all
<input type="checkbox" name="viju" id="viju" value="Jan" onClick="">jan
<input type="checkbox" name="viju" id ="viju" value="feb" onClick="">feb
<input type="Button" value="Show values" onClick="checkedAll(this.value)"/>
Jsfiddle http://jsfiddle.net/2UFdc/
HTML
<form>
<input type="checkbox" name="causelist_month" id="causelist_month" onclick="checkedAll ();">select all/unselect all
<input type="checkbox" name="viju" id="viju" value="Jan" onClick="">jan
<input type="checkbox" name="viju" id ="viju" value="feb" onClick="">feb
<input type="Button" value="Show values" onClick="showVal(this.form)"/>
</form>
Javascript
var checked = false;
function checkedAll() {
var c = document.getElementsByName("viju");
checked = document.getElementById('causelist_month').checked;
for (var i = 0; i < c.length; i++) {
c[i].checked = checked;
}
}
function showVal(frm) {
var arr = [];
for (var i in frm.viju) {
if (frm.viju[i].checked) {
arr.push(frm.viju[i].value);
}
}
alert(arr);
return arr
}
First, use the event listener for the checkboxes rather than onClick:
document.getElementById("causelist_month").addEventListener('change', function(){
checkboxes = document.getElementsByName("viju");
for( var i=0; i<checkboxes.length; i++){
checkboxes[i].checked = this.checked;
}
}, false);
And for the display of the checked items, in HTML:
<input type="Button" value="Show values" onClick="displayChecked()"/>
<div id="display"></div>
Then, in javascript:
function displayChecked (){
var display = "";
checkboxes = document.getElementsByName("viju");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display += " " + checkboxes[i].value;
}
}
document.getElementById("display").innerHTML = display;
}
you could use jquery functions
dont forget to inclde jquery library
<button id="showall"> display </button>
`
$("#showall").click(function() {
var array = [];
$(':checkbox:checked').each(function(i){
array[i] = $(this).val();
});
$.each( array, function( i, val ) {
$("#display").append(val); //the div where you want to display
});
});
`
<!DOCTYPE html>
<html>
<script>
var checked=false;
function checkedAll()
{
var c = document.getElementsByName("viju");
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<c.length; i++) {
// And stick the checked ones onto an array...
if (c[i].checked) {
checkboxesChecked.push(c[i]);
}
}
if(document.getElementById('causelist_month').checked)
{
checked = document.getElementById('causelist_month');
checkboxesChecked.push(checked);
}
for (var j=0; j<checkboxesChecked.length; j++) {
// iterate the pushed values
alert(checkboxesChecked[j].value);
}
}
</script>
<body>
<form>
<input type="checkbox" name="causelist_month" id="causelist_month" value="select all/unselect all" onclick="checkedAll ();">select all/unselect all
<input type="checkbox" name="viju" id="viju" value="Jan" onClick="">jan
<input type="checkbox" name="viju" id ="viju" value="feb" onClick="">feb
<input type="Button" value="Show values" onClick="checkedAll(this.value)"/>
<form>
</body>
</html>
This displays all the list of check boxes in the alert message one by one. please check

Categories

Resources