Get value of multiple choices checkboxes Javascript - javascript

I'm using the onsubmit event on a form to verify it before it is sent. I'm having issues getting the value of checkboxes that allows multiple choice.
Html:
<input type="checkbox" name="question5[]" value="1" />
<input type="checkbox" name="question5[]" value="2" />
Javascript:
var form = document.forms['questionnaire'];
var q5 = form.elements["question5"].value;
When I try to get the value of this question I'm not able to retrieve it the same way I did for the other fields. I'm wondering what is the correct way to get the value of those checkboxes since I can't retrieve it like a radio or text input.

The name of the field is question5[] not question5 and since you have multiple of them, you will get a NodeList (which is like an Array) back, not a single Element.

Related

How to get POST form data that have dynamic IDs?

I have checkboxes inside a form. These checkboxes are a list of persons dynamically created since this list depends on who is logged in. Like, for a supervisor view, it will only list your subordinates.
I'm not sure if I'm missing something but the docs and other answers in SO are all saying that you have to have the id of the input in order to retrieve the form data but in my case, I used the person's ID in the list to come up with the name of the checkbox element. So my checkbox names are like input-{{person_id}}
Now in the post method, I'm not sure how to retrieve the checkboxes in the form. Tried using self.__dict__ but I can't seem to find anything that I can use
link1 - this specifies the name
link2 - this also says that the ID should be pre-determined
link3 - docs also say that if the parameter is not included, an empty list would returned
Maybe there is a workaround where I just get all the elements in the form and make them seen in tornado? Using javascript maybe?
I'm mistaken, it seems that if you use the same name for a checkbox element for all the dynamic checkboxes you create, then when you submit it to the tornado web handler, it will get the values of all those checkboxes that have that name.
the values are retrieved by using the get_arguments
Is this how you mean?
HTML
<form>
<input type="checkbox" id="box1" name="Name1" checked>
<label for="box1">Name 1</label>
<input type="checkbox" id="box2" name="Name2">
<label for="box2">Name 2</label>
</form>
jQuery
$("form input[type='checkbox']").each(function() {
console.log($(this).attr('name'))
})
Output
"Name1"
"Name2"
You can loop through the request.body_arguments attribute; it's dict which maps arguments names to lists of values (to support multiple values for individual names).
class MyHandler(tornado.web.RequestHandler):
def post(self):
for key, value in self.request.body_arguments.items():
print(f"key {key} has value: {value}")
...
There are also arguments (holds both query and body args) and query_arguments (holds only query args) attributes; you can check the docs here.

Get checked elements outside of submitted form with HTML

I have a web page, at the top is a set of radio buttons and a submit button. Here is the code for that:
<form action="/batch" method="POST">
With checked selection you may:
<input type="radio" name="bulk" value="broadcast">Broadcast</input>
<input type="radio" name="bulk" value="unbroadcast">Unbroadcast</input>
<input type="radio" name="bulk" value="delete">Delete</input>
<input type="submit" value="Run batch on checked items" />
</form>
Below that i have a table consisting of a bunch of rows with checkboxes at the beginning. Code for that is:
<td><input type="checkbox" name="{{ md5_name }}" class="box"/></td>
Is there a way to have the form submit a list of what the checkboxes are and whether they're checked regardless of the fact that the checkboxes are not within the form? Perhaps naming it the same or shared class?
While searching around before posting i found the following snippet from this page which looked promising, but i don't know how running it alongside my POST method would work, or how i would include the result in my POST method.
function getRadioValue (theRadioGroup)
{
for (var i = 0; i < document.getElementsByName(theRadioGroup).length; i++)
{
if (document.getElementsByName(theRadioGroup)[i].checked)
{
return document.getElementsByName(theRadioGroup)[i].value;
}
}
}
You could, in the HTML 5 doctype, simply associate those form-elements with a specific form, using the form attribute:
<td><input form="formElementID" type="checkbox" name="{{ md5_name }}" class="box"/></td>
This attribute:
Indicates the form that is the owner of the element1
References:
MDN: HTML Attribute reference.
Bibliography:
HTML forms reference.
You could bind a function to the submit method of the form to retrieve the values of the checkboxes, and add them into hidden fields in the form.
Alternately add the default values of the checkboxes to hidden fields, and bind a change method to the checkboxes to update the hidden field.

Get values of all checked radio buttons using JQuery

Using JQuery I am trying to perform validation and also get the values of all the dynamically generated Radio buttons in the page.
I have 10 questions on my page and each question has a Radio button group(YES/NO).
when click in the radio button i want to send it's value to database for the question, this is my code
<p>Question 1</p>
<input id="1_1" type="radio" name="1" value="Yes" />
<input id="1_2" type="radio" name="1" value="NO" />
i searched in google and found this code
$('input[name=radioName]:checked', '#myForm').val()
But I don't know what is the right way to use it ?
As per your HTML structure try this :-
var arr = []; // take an array to store values
$('input[type="radio"][name="1"]:checked').each(function(){
arr.push($(this).val()); //push values in array
});
If you want the values of all <radio> you can do
var ans = $('[name=1]:checked').map(funciton(){
return $(this).val();
}).get();

How to enable HTML elements on submit

I have a checkbox and a few input elements related to this checkbox as shown below
<input name="balanceFeaturesOn" id="balanceFeaturesOn" type="checkbox" disabled="disabled" checked="" />Control
<input name="IntervalDays26566521" type="Text" onclick="" onchange="" value=" 31 ">
<input name="IntervalHours26566521" type="Text" onclick="" onchange="" value=" 12 ">
For some reasons, I will have to keep my checkbox always disabled.
On the submit of above form (Say that the checkbox and inputs are inside a form), in the server code, I want to grab the text inputs based on if the checkbox was checked/unchecked. However since the checkbox is disabled, the request parameter does not contain the balanceFeaturesOn property.
So when I execute the below line:
String[] balanceFeatArr = request.getParameterValues("balanceFeaturesOn");
I am not getting any value...
So my question is how do I be able to get the value of the checkbox while still keeping it disabled on the UI?
Try the following code,
In the form use javascript function to submit the form,
<input type='submit' onclick='javascript:submitMe()' />
Javascript function,
function submitMe(){
$('#balanceFeaturesOn').removeAttr('disabled');
$('#formId').submit(); //Replace with the actual id of the form
}
Make sure you have included jquery library in your code.
Use Hidden Fields.
Hidden fields are similar to text fields, with one very important difference!
The difference is that the hidden field does not show on the page. Therefore the visitor can't type anything into a hidden field, which leads to the purpose of the field:
To submit information that is not entered by the visitor.
http://www.echoecho.com/htmlforms07.htm

Setting java string variables value depending on html checkbox selected

I have two check boxes with table names when any check box is checked i wants to save that table name in to a java string which i can use in the query to get data from that table or update that table.
I have used onClick functions and also got the check box value but not getting how to access it in the rest of the code so that i can use that value in the DB query.
I assume you have HTML code like the following:
<input type="checkbox" name="use_table1" />
<input type="checkbox" name="use_table2" />
On the server-side Java code, you can then query:
String tableName = null;
if (request.getParameter("use_table1") != null)
tableName = "tbl_1";
if (request.getParameter("use_table2") != null)
tableName = "tbl_2";
Note that the "outside" names differ from the real table names. No one out there on the web should need to know your real table names. And, most important, no one should be allowed to read an arbitrary table from your database. That's why I used that if-then-else code to select the table name.
Just give the table name as value. The browser will send only the name-value pairs of the checked ones as request parameters.
<input type="checkbox" name="tablename" value="table1">
<input type="checkbox" name="tablename" value="table2">
<input type="checkbox" name="tablename" value="table3">
<input type="checkbox" name="tablename" value="table4">
In the Servlet, you can grab them by HttpServletRequest#getParameterValues().
String[] checked = request.getParameterValues("tablename");
Simple as that :) No need for unnecessary JavaScript hacks/workarounds which ain't going to work in JS-disabled clients. This is one of the many unknown features of HTML.

Categories