I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
Related
I have a comment system in which i want to add delete option, for this i have implemented a POST form in each comment which posts comment-id to delete.php, it is working in php, but not in jquery.
i.e in order to delete comment a comment id must be posted to delete.php file which handles deletion of comment from database.
i am trying to fetch that comment-id from input value to post with jquery like this but it gives me the first comment-id value not the selected value.
Jquery
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]").val();
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
repeating form is like this
<form name="comments" action="../../delete.php" method="post">
<input name="comment-delete" type="hidden" value="<?php echo $list['comment-id']; ?>" />
<input value="Delete" type="submit" />
</form>
if i use .each() or .map() it gives me all the comment-id values.
Please see and suggest any possible way to do this.
Thanks.
To find the relevant input, that is the one of the form you submit, you could use this :
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
BTW, I'm not totally sure of what you do but you might be missing a .val() to get the value of the input.
You have the same name on each hidden input, naturally you get all those inputs as you have not targeted the correct form when doing:
$("input[name=comment-delete]");
"this" whould point to the form inside your submit function. Try this.
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
As dystroy said, you are probably missing .val().
var commentId = $(this).find("input[name=comment-delete]").val();
try this
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]", this);
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
this refers to the form being submitted (more generally, to the event source).
$(...) accepts a second parameter, which is then used as a context for the selector. $(selector, context) is equivalent to $(context).find(selector)
Trying to make the infamous checkall checkbox for dynamically created rows from a MySQL query. Rows (and therefore checkboxes) could range from 1 row to a metric buttload.
The form (without the checkall) is as follows:
<form name="form" method="post" action = "process.order.php">
<?php
while($fetch = mysql_fetch_array($order_query){
$order_id = $fetch['oid'];
$order_status = $fetch['ostat'];
?>
<input type="checkbox" name="order_row[<?=$order_id?>]" id="1" value="1">
<select name="status[<?=$order_id?>]" id="status[<?=$order_id?>]"
<option value="Ordered">Ordered</option>
<option value="Backordered">Backordered</option>
</select>
<? } ?>
<input type="submit" name="submit" id="submit" value="submit"> </form>
In process.order.php:
<?php
if(is_array($order_row)){
foreach($order_row as $order_id=>$val){
...followed by the rest of the script. I tried using this: How to implement "select all" check box in HTML?
and this:
Select All Checkbox
I'm trying to avoid using jQuery at this moment. Is there a way I can call the checkbox name generated by the PHP script into the javascript code?
Update:
I'd like to use a function that I can call across multiple pages. Thus, calling embedding the form name in the JS won't be practical for me. Also, I'd like it to be a checkbox - the button's worked great, but I'm trying to keep the UI simple and I already have a lot of buttons I'm trying to get rid of...
Working Example
You can do like this:
var frm = document.forms['form'];
for (var i = 0, l = frm.elements.length; i < l; i++) {
if (frm.elements[i].type === 'checkbox') {
frm.elements[i].checked = true;
}
}
Similarly, to uncheck all set:
frm.elements[i].checked = true;
to false.
You can also easily create checkAll and unCheckAll functions using above code.
By the way, an id with only numeric value is invalid, you should use alpha or mix of alpha and numeric characters.
If you don't have to support IE6 or 7, the following will work.
Live Demo
var checkAll = document.getElementById("checkall");
checkAll.onclick = function(){
[].forEach.call(
document.forms['form'].querySelectorAll("input[type='checkbox']"),
function(el){
el.checked=true;
});
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript post request like a form submit
I have a value calculated in JS that I'd like to pass as part of an input form to a PHP script. How can I get a value the JS value to the PHP as a POST parameter?
Basically, on submit, I need the total var to be passed via post to the next script.
The first idea that comes to mind is create an invisible input form that has the value in it and is inputted with the form, is that possible?
There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.
create this form element inside your form:
<input type="hidden" name="total" value="">
So your form like this:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
Click to submit
</form>
Then your javascript something like this:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
Yes you could use an <input type="hidden" /> and set the value of that hidden field in your javascript code so it gets posted with your other form data.
You can do this using Ajax. I have a function that I use for something like this:
function ajax(elementID,filename,str,post)
{
var ajax;
if (window.XMLHttpRequest)
{
ajax=new XMLHttpRequest();//IE7+, Firefox, Chrome, Opera, Safari
}
else if (ActiveXObject("Microsoft.XMLHTTP"))
{
ajax=new ActiveXObject("Microsoft.XMLHTTP");//IE6/5
}
else if (ActiveXObject("Msxml2.XMLHTTP"))
{
ajax=new ActiveXObject("Msxml2.XMLHTTP");//other
}
else
{
alert("Error: Your browser does not support AJAX.");
return false;
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4&&ajax.status==200)
{
document.getElementById(elementID).innerHTML=ajax.responseText;
}
}
if (post==false)
{
ajax.open("GET",filename+str,true);
ajax.send(null);
}
else
{
ajax.open("POST",filename,true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(str);
}
return ajax;
}
The first parameter is the element you want to change. The second parameter is the name of the filename you're loading into the element you're changing. The third parameter is the GET or POST data you're using, so for example "total=10000&othernumber=999". The last parameter is true if you want use POST or false if you want to GET.
Your idea of an hidden form element is solid. Something like this
<form action="script.php" method="post">
<input type="hidden" name="total" id="total">
</form>
<script type="text/javascript">
var element = document.getElementById("total");
element.value = getTotalFromSomewhere;
element.form.submit();
</script>
Of course, this will change the location to script.php. If you want to do this invisibly to the user, you'll want to use AJAX. Here's a jQuery example (for brevity). No form or hidden inputs required
$.post("script.php", { total: getTotalFromSomewhere });
I have a simple checkbox on a page that allows a user to say if they'd like to receive email notifications. I am using jquery for this to call some php code when the checkbox changes. However, I am not having much luck even calling the jquery function (clicking the checkbox does nothing) let alone test the backend functionality.
Any help in pointing out the error would be great. Thanks.
The checkbox HTML:
<input id="notify_checkbox" type="checkbox" value="y" name="notify">
The jquery:
$('#notify_checkbox').change(function(){
if($('#notify_checkbox').attr('checked'))
{
$.post("/update_notify", { checked: "y", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
else
{
$.post("/update_notify", { checked: "n", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Okay, we won't email you.</p>" );
}
});
And finally the PHP:
function update_notify()
{
// Passed through AJAX
$notify = $_POST[checked];
$email = $_POST[email];
$this->load->model('musers');
$query = $this->musers->update_user_notify($email, $notify);
}
RESOLUTION: The comments below were helpful but not the ultimate solution. The solution was to add the following around my code.
$(document).ready(function() {
{);
Why not use .click() instead?
JSFIDDLE
Also, as you can see in my JSFiddle example, use .is(':checked') instead of attr('checked').
edit after #Rocket commented on your post:
You should indeed quote your $_POST values in your php! Didn't notice it myself, credits to rocket
What's the name of your controller? You need to put that in the URL.
$.post("/controller/update_notify", ...
The problem is with the redefinition of the attr function in jQuery 1.6, and with the difference between attributes and properties.
With attributes (retrieved with attr), the value of checked="checked" or its absence stays the same, regardless of whether the element is actually checked or not.
With properties (retrieved with prop as of jQuery 1.6), the actual state of the element is found. This is equivalent to checking the checked property of the element (which is preferable because you don't need to do a new jQuery selection). The best soltion would be as follows:
if (this.checked) {
See jsFiddles showing this:
your current solution
using prop
using this.checked
I'm building a search form with several filter options on the results page.
It's a basic search form, results show in an friendly url such as: domain.com/resuts/country/age/type/
The filters are simply checkboxes which on click, should reload the page with a query string to identify what has been checked/unchecked. (there is no submit, preferably the update would rebuild the query string with every check box click).
So, for example, on click of some checkboxes we'd build a query string on the end,
eg:domain.com/resuts/england/20-29/female/?scene=hipster&status=single
Can anybody point me to a jquery resource or a code snippet which may assist in getting this done?
Many thanks,
Iain.
The jQuery.get function will automatically handle creating and building the query string when you pass a key-value pair:
http://docs.jquery.com/Ajax/jQuery.get
You can use this selector for checked checkboxes:
$('input:checkbox:checked')
If your html looks like
<input type="checkbox" name="scene" value="hipster" />
I guess you can use something like
var tmp = [];
$('input:checkbox:checked').each(function(){
tmp.push($(this).attr('name') + '=' + $(this).val());
});
var filters = tmp.join('&');
$('.checkbox_class').change(function () {
let filter = $('.checkbox_class');
let types = [];
$.each(filter, function( index, input ) {
if(input.checked)
{
types[index] = input.value;
}
});
let typeQueryString = decodeURIComponent($.param({type:types}));
console.log(typeQueryString);
});
Is this what your looking for? When you click the checkboxes it shows the selected values up top. when you submit the form it shows you the same value in an alert
<div id="buffer" style="height:2em; border:1px solid black; margin-bottom:1em"></div>
form action="#" method="get">
input type="checkbox" id="j" name="state" value="state">state
input type="checkbox" name="city" value="city">city
input type="checkbox" name="type" value="type">type
input type="submit" value="click me">
/form>
$().ready(function(){
//just a simple demo, you could filter the page by the value of the checkbox
$('form input:checkbox').bind('click',function(){
if($(this).attr('checked')==false){
//remove it from the query string
var pieces=$('#buffer').text().split('/');
var $this_val=$(this).val();
for(var i=0;i<pieces.length-1;i++){
//console.log($(this).val());
//console.log(pieces[i]);
if(pieces[i]==$this_val){
//remove value from the buffer
pieces.splice(i);
}
$('#buffer').text(pieces.join('/')+'/');
}
}else{
//add the value to the query string
$('#buffer').append($(this).val()+'/');
}
});
//on form submit
$('#filterWrapper form').submit(function(){
var queryString='';
$.each($('form input:checkbox:checked'),function(){
queryString+=$(this).val()+'/';
});
alert('this will get send over: '+queryString);
return false;//remove this in production
});
Sorry about the broken HTML, the editor doesnt like form tags and input tags