Save and Load Checkbox checked states to database - javascript

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');
}
});

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.

Get value of multiple choices checkboxes 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.

Passing values of checkboxes to Perl Script

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.

Getting checked value with ajax submit

First of, I'm new to ajax and Java Script.. I have spend days solving this problem, but I still haven't figured it out. I have read through threads with similar problems but I still can't get it right. So here goes;
Quite simple I want post the checked value from from one of three radio buttons. All I get though is only the value of the first radio button..
I have tried several things, but I stripped down the code so it might be easier see where the problem is :-)
The ajax
<script type"text="" javascript"="">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var svar = $('#svar').attr('value');
var date = $('#date').attr('value');
var email = $('#email').attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "svar="+ svar + "&email=" + email + "&date=" + date,
success: function(){
$('form#submit').hide();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
</script>
The form
<form id="submit" method="post" name="submit" action="">
<fieldset>
<legend>Dagens spørgsmål: <? echo $row['question'];?></legend>
<br>
<input type="radio" name="svar" id="svar" value="1"><? echo $row['opt1'];?>
<br>
<input type="radio" name="svar" id="svar" value="2"><? echo $row['opt2'];?>
<br>
<input type="radio" name="svar" id="svar" value="3"><? echo $row['opt3'];?>
<br>
<input name="email" id="email" type="hidden" value="<? echo $email ?>" />
<input name="date" id="date" type="hidden" value="<? echo $date ?>" />
<br><br>
<button type="submit" class="button positive"> <img src="img/tick.png" alt=""> Svar på dagens spørgsmål </button>
</fieldset>
</form>
Ajax.php
<?php
include ("dbc.php");
// CLIENT INFORMATION
$email = htmlspecialchars(trim($_POST['email']));
$date = htmlspecialchars(trim($_POST['date']));
$svar = htmlspecialchars(trim($_POST['svar']));
//stuff from answers
mysql_query("INSERT INTO answers
(`email`,`day`,`answer`)
VALUES
('$email','$date','$svar')") or die(mysql_error());
?>
Hope one you of you smart guys have a solution.. because this thing i driving me crazy
You have several problems.
First, your HTML is invalid. An ID must be unique, so each radio button must have its own ID. You associate a group of radio buttons by giving them the same NAME. (Having a unique ID then lets you associate a LABEL with each one using the FOR attribute which increases accessibility by making it easier for screen readers and providing bigger click targets).
Second, the value of a radio button is fixed. The question is "Is it successful or not?" and that is determined by seeing if it is checked or not. If you were doing this manually, you would have to loop over each radio button in the group until you found one that was checked (or use a selector that matched only the checked ratio button (:checked)).
Third, you are building your form data by mashing together strings without making sure the data is URL safe (with encodeURIComponent).
The solution is to forget about doing all this manually and just use the jQuery serialize method on the form.
First: you use the same id for several elements. ID-s should be unique, and you should address your elements with class name or other means. So instead of
$('#svar')
yous should use
$('input[name=svar]')
to reference the group of checkboxes.
Second: There is a slight mistake here:
$('#svar').attr('value');
is the value of the first radio button's value attribute, while
$('input[name=svar]:checked').val();
would give you the value of the checked radio button in the group you are selecting with input[name=svar].
Edit: thx #Quentin for pointing out my error.
First thing to know is id should be unique in a html document.
What makes attributes of type ID special is that no two such
attributes can have the same value;
[Quoted from css2 selector docs]
You have assigend same id to three radio buttons.
Now when you use var svar = $('#svar').attr('value');, only the first radio button will get selected. So, irrespective of radio button selected, only the first radio buttons value you will get.
Now, if you want to get the radio button selected you have to use jQuerys :checked selector.

Categories