I'm missing something in my code. I have a list of text boxes that are meant for percentage values, and there could be numerous inputs.
// loop through unknown inputs with different values
<input name="DESIREDPERCENT[<?php echo $recid; ?>]" class="percinputbox" />
// end loop
// attach click event to this element
<span id="updatepercs">Update Percentages</span>
I then have a simple span element to send all the inputs with the class percinputbox
$(document).ready(function(){
$('#updatepercs').click(function(){
var allinputs = $("input.percinputbox").serialize();
console.log(allinputs); //DESIREDPERCENT%5B73%5D=50.00&DESIREDPERCENT%5B104%5D=50.00
$.ajax({
url:'update.php',
data:"formId=updatepercentages" + allinputs,
success:function(response){ alert(response); }
});
});
I have my php listening for the $.ajax:
update.php
<?php
if($_POST['formId'] == 'updatepercentages'){
foreach( $_REQUEST['DESIREDPERCENT'] as $key ){
echo $key;
}
}
?>
So far I'm only getting one input value. So I'm definitely doing the sending wrong.
I'm open to a better/optimized way here. I generally use the <form> tag to submit forms, but I want to know how to submit these inputs with jquery.
You are missing an & between formId=updatepercentages and allinputs
data:"formId=updatepercentages&" + allinputs,
Related
I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.
I have dynamically created an array of checkboxes in PHP for a form, but I don't want the Submit button to appear unless at least one checkbox is checked. Scouring the Internet most people who want the Submit button to only appear after checking a checkbox only have one "I agree" checkbox. Is it the dynamic creation that is preventing my script working?
PHP↴
// Dynamically create checkboxes from database
function print_checkbox($db){
$i = 0;
foreach($db->query('SELECT * FROM hue_flag') as $row) {
if ($i == 0 || $i == 3 || $i== 6 || $i == 9){
echo '<br><br>';
}
$i++;
echo '<span class="'.$row['1'].'"><label for="'.$row['1'].'">'.ucfirst($row['1']).'</label><input type="checkbox" name="hue[]" id="hue" value="'.$row['0'].'"></span> ';
}
}
jQuery↴
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hue[]').click(function(){
$('#input_gown').toggle();
});
});
</script>
PHP function call↴
<?php print_checkbox($conn_normas_boudoir);?>
Admittedly I know nothing about jQuery or JavaScript and am still learning PHP. So, if there's a better way to implement this, let me know.
You're giving all your checkboxes the same ID. That's not allowed; IDs have to be unique.
An easy solution to both problems is to assign all the checkboxes a common class:
echo '<span class="'.$row['1'].'"><label for="'.$row['1'].'">'.ucfirst($row['1']).'</label><input type="checkbox" name="hue[]" class="hue" value="'.$row['0'].'"></span> ';
Then select the class in jQuery:
$('.hue').change(function(){
$('#input_gown').toggle();
});
But that may give unexpected results; what if two checkboxes are checked? The #input_gown element will toggle on and off again. Perhaps you only want it shown if at least one checkbox is checked:
$('.hue').change(function(){
var val = false;
$('.hue').each(function() {
val = val || $(this).is(':checked'); // any checked box will change val to true
});
$('#input_gown').toggle(val); // true=show, false=hide
});
http://jsfiddle.net/mblase75/AyY3Z/
Your jQuery selector is looking for elements with id hue[]. But your elements have the id of just hue.
Change this:↴
$(document).ready(function(){
$('#hue[]').click(function(){
$('#input_gown').toggle();
});
});
to this (IDs should really always be unique, and the square brackets will need to be escaped to work with the selector engine), (a demo)):↴
$(document).ready(function(){
$('input[name=hue\\[\\]]').click(function(){
$('#input_gown').toggle();
});
});
I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.
I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com
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