Passing values of checkboxes to Perl Script - javascript

I have a simple list of checkboxes, which are NOT in a form. On clicking a button, I want to send the values of all selected checkboxes to a perl script. I do not want to make it a form. Am working with ExtJS and thus don't need any jQuery solutions or hints. Any tips to how I do this?
Illustration :
<input type="button" class="check" value="Send" onclick="foo()"/>
<input type="checkbox" name="chk" value="1"/> Checkbox 1
<input type="checkbox" name="chk" value="2"/> Checkbox 2
<input type="checkbox" name="chk" value="3"/> Checkbox 3
On clicking "Send", I want to write the function foo() so that it can pass the selected values to my perl script hw.pl.
EDIT : I understand that I have to send the parameters using the GET method. But after I wrote the JS function, and have the checked values in a JS array, how do I send that array as a GET parameter?
I wrote the following foo() function, but it doesn't work :
function foo(){
var tclist = "";
for(var i = 0; i < chk.length; i++)
if(chk[i].checked)
{ tclist += chk[i].value + ","; }
self.location='/cgi-bin/hw.pl?tcs=tclist';
}
Any help would be greatly appreciated. I am new to CGI scripting.

Change
self.location='/cgi-bin/hw.pl?tcs=tclist';
to
self.location='/cgi-bin/hw.pl?tcs=' + tclist;
But please take a look at the other comments. First off, you should be using a form. Second, why use JavaScript at all? If you stuff your checkboxes in a form, their values will be submitted without any client side scripting.

Related

Get values submitted to php from form

Consider the following form:
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo">
<input type="checkbox" value="1" name="foo">
</form>
When submitting the form, the URL ...?foo=0 will be requested if the checkbox is not checked. If the checkbox is checked, the URL ...?foo=0&foo=1 will be requested. In PHP, query string arguments override any previous arguments with the same name, so foo will have the value 1 in the PHP script handling the latter request.
What is the best way to obtain the value foo would have in the PHP script using JavaScript, when not knowing anything about the form? In theory, there could be an arbitrary number of inputs named foo of different types, and I would like to know the value that foo would have in the PHP script handling the request if the form was submitted.
As I understand it, the answer is the value of the last enabled input element named foo. By enabled, I mean that the input element is not disabled and that it is not a button (the button's name and value are not added to the query string unless the button is used to submit the form) or an unchecked checkbox or radio button.
Maybe there is an easy way to get this value using jQuery?
Edit
Loads of people suggest that I rename the input elements to foo[] or similar. I guess I was not clear enough that I actually want all the input elements named foo, and to only receive one of the values in the php script.
My questions is how to determine which value the php script will receive using JavaScript.
use this:
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo[]">
<input type="checkbox" value="1" name="foo[]">
</form>
and in PHP, use:
$params = $_GET['foo']; //params would hold array
it would be good to use.
You can do a loop on the global variable $_GET
foreach($_GET as $key=>$val) {
echo "key = $key , val = $val";
}
if you have multiple inputs with the same name you will need to append []to the name so you can get all the values as a array
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo[]">
<input type="checkbox" value="1" name="foo[]">
</form>
to get the values in jquery you do the following:
$('input[name="foo[]"]').each(function(){
console.log($(this).val());
});
if you only want one value of foo but you have multiple elements with that name you will need to change your logic to using radio buttons
This is really bad design. You should check checkbox state in your php (backend) code. Get rid of the hidden input:
<form method="get" enctype="multipart/form-data">
<input type="checkbox" value="1" name="foo">
</form>
and put this in your php code:
if (isset($_GET['foo'])) {
$foo = 1;
} else {
$foo = 0;
}
If you want to use javascript, you can try this on form submit:
var checkboxValue = $("input[name='foo']").prop("checked");
checkboxValue would be true or false depending on checkbox status.

condition for an MVC checkbox in javascript

I have a checkbox in an MVC project called:
#Html.CheckBox("ShowAll", true)
and then in my js I want to check if the checkbox is checked or not.
Something like
function checkboxAll(item)
{
if ((showAll).isChecked)
{
//do stuff
whats the best way? I cant seem to get the syntax right
Thanks
}
}
When using #Html.Checkbox the first parameter is the html attribute "name" that will be applied when the checkbox is created.
If you retrieve a DOM element from a html attribute you can use the following jquery:
var isChecked = $("[Name='ShowAll']").val()
P.S. I can't guarantee this is correct and will edit comment later if it is.
So if you write #Html.CheckBox("ShowAll", true) this renders a checkbox with below properties.
<input checked="checked"
id="ShowAll"
name="ShowAll"
type="checkbox"
value="true" />
Also it generates a hidden input like this:
<input name="CheckBox" type="hidden" value="true" />
Now you know how to get a field by name or id in jquery.
access value by
$("input[name='ShowAll']").val()
or is checked
$("input[name='ShowAll']").is(':checked')
or by pure js var chkbox = document.getElementsByName("ShowAll");
See the msdn page for complete overloads.

Save and Load Checkbox checked states to database

I have a "settings" page in my site and I would like the user to be able to either check or uncheck checkboxes in the settings page. The checkboxes' states should then load when the user logs in.
My idea is to assign ids to each checkbox like this:
<input type="checkbox" id="chk1" data-col='column1' value="0"/>
<input type="checkbox" id="chk2" data-col='column2' value="0"/>
and then use jQuery to set the values for each on the checked function like this on the "SAVE SETTINGS" button:
$( "input:checkbox" ).each(function() {
if $(this).prop('checked'){
$(this).prop('value','1')
}
});
and then have a column in my MySql table for each checkbox and then send the value (either 1 or 0) to my database via ajax/php.
Then when the user logs in, I can get the values (1 or 0) for each column and then based on that, I can set the checked state.
Is this a good way to go about it? I want to make sure I don't go down the wrong path if there is a simpler solution or approach.
Assume that $query_array is the container of your db query. Since you've included php in the post's tag you can insert a php tag inside input(assuming the file is a php too):
<input type="checkbox" id="chk1" data-col='column1' value="<?php echo $query[0][col_name];?>"/>
^the 0 above might be an id, and col_name is the column name which contains 0/1
When that is compiled, it should be similar to this:
<input type="checkbox" id="chk1" data-col='column1' value="0"/>
Instead of using jquery why don't you just render the checkboxes with their value already set:
<input type="checkbox" id="chk1" data-col='column1' value="<?php echo $chk1?>" <?php echo $checked?>/>
Edit
If you wanna keep it HTML only you could store the states in a JSON (where the property name is the id of the chekbox and the value it's state) and loop through it as:
$.each(jsonChkbxValues, function(index, val) {
var elem = $('#' + index);
elem.prop('value', val);
if (val) {
elem.attr('checked', 'checked');
}
});

How to recursively check checkboxes by array values?

I am going to try to be as concise as I can :) I am working on a project. This project generates many pages full of thumbnail images with checkboxes next to them. There can be a varying ammount of total thumbnails. The thumbnails are sorted into 1000 item html pages. So 1000 thumbnails an html page. These pages full of thumbnails are called by a parent html page via iframe. My goal is to have the ability for a user to check checkboxes near these thumbnails, then load a new page into the iframe, checkboxes there, then be able to load the previous page into the iframe, and for the javascript to check the boxes the user had previously checked. I keep track of which checkboxes the user checked by using an array.
Here is the javascript. There is TWO issues! First issue is, I have the alert there for debugging. It does alert the correct values, but it alerts all of the values stored in the array. I wish it to only alert the checkboxes that exist within the iframe page, which is why I have it to the document.getElementByNames. Then... it doesn't check any of the boxes! No box checks :(
Any thoughts on how to accomplish this? the JS and HTML is below...
JS
function repGenChk(valNam) {
var chkN = valNam.name;
parent.genL.push(chkN);
alert(parent.genL);
}
function chkSet() {
for (var i = 0; i < parent.genL.length; i++) {
var item = parent.genL[i];
var item = document.getElementsByName(item);
if (item != null) { document.getElementsByName(item).checked=true; }
alert(parent.genL[i]);
}}
window.onload = chkSet();
HTML
<input type="checkbox" onClick="repGenChk(this);" value="1" name="1">
<input type="checkbox" onClick="repGenChk(this);" value="2" name="2">
<input type="checkbox" onClick="repGenChk(this);" value="3" name="3">
<input type="checkbox" onClick="repGenChk(this);" value="4" name="4">
so on and so forth for Xthousands of checkboxes....
Any thoughts, ideas, constructive criticism and critiques are EXTREMELY welcome! I've gotten alot of jQuery suggestions in the past, and i'm heavily starting to consider it.
Thanks so much everyone!
EDIT - I was able to figure it out. I didn't think I could use IDs with checkboxes, I can. Woo!
JS
function repGenChk(valNam) {
var chkN = valNam.id;
parent.genL.push(chkN);
alert(parent.genL);
}
window.onload = function chkSet() {
for (var i = 0; i < parent.genL.length; i++) {
if (document.getElementById(parent.genL[i]) != null) { document.getElementById(parent.genL[i]).checked=true; }
}
}
HTML
<input type="checkbox" onClick="repGenChk(this);" id="1">
<input type="checkbox" onClick="repGenChk(this);" id="2">
<input type="checkbox" onClick="repGenChk(this);" id="3">
<input type="checkbox" onClick="repGenChk(this);" id="4">
etc etc etc.....
:)
Consider putting a single click listener on an element containing the checkboxes. Give each checkbox a unique id or name. When you get a click on the container, check where it came from. If it's from a checkbox, add or remove the name/id of the checkbox to an object storing which ones are checked depending on whether the checkbox is checked or not.
When you want to re-check them, iterate over the object (using for..in) and use getElementById or getElementsByName(…)[0] to check the checkbox. That way you only iterate over as many object properties as there are checked checkboxes and also getElementById is very fast, so things should be simpler and faster.
BTW, getElementsByName returns a collection, which is array-like but it isn't an array.

Java Script issue while submitting a form through JSP

I am facing an issue when I am trying to submit a JSP page .
I will describe in short the scenario so that it would be clear.
The Scenario
I have some input elements made up in a html component on JSP page.
The table has many <tr>. These <tr> have been given ids, for e.g. <tr id="1">.
Now I am trying to pass a comma separated list of these tr ids to server side code or Servlet.
The comma separated list is formed with looping some logic on submit of JSP or more specifically a form.
The Problem:
When I submit the form sometimes I do not receive the comma separated values mentioned above at server side code.
This happens occasionally. Now when I put some delay through Java Script like setTimeOut() I do not face the issue.
So can anyone please help me guiding on this?
Is Java Script behavior a bit non-sequential sometimes?
Thanks in advance.
JavaScript execution is sequential as long as you do NOT use asynchronous mechanism (e.g. Timer, Ajax, etc).
So the question is how you submitted the form. I've ever written code of similar function and I never encountered the problems you mentioned.
Here I provide my solution. Hope this can help.
I don't use a <input type="submit" /> to submit my form. Instead, a common button is employed with an onclick event binding:
<form id="form1" action="serverscripturl" method="post">
<input type="button" value="submit" onclick="form1submit()" />
<input id="field1" name="field1" type="hidden" />
</form>
Then I use a JavaScript function to perform the concatenation and submission:
function form1submit(){
var list = ""; // your comma separated list
for (var i = 0; i < data.length; i ++)
list += (data[i]+",");
// set the value of field1 the list
document.getElementById("field1").value = list;
document.getElementById("form1").submit(); // submit the form<br>
}
and on server side script like response.getParameter("field1") will work.
Hope this can help you.

Categories