javascript checkbox not reacting when clicking, always have to press submit - php

For some reason I can't get to work a script I have been trying out for a few days.
I have some checkboxes that show different colors. When the user clicks on one color I want the script to reload one of the DIVs of my website.
Everything works fine with the <form> tags and an <input type="submit">, basically with a button. But it never works by just checking a checkbox, I always have to click on submit.
Any help with the code would be much appreciated!
Thanks!
javascript:
<script>
$('.colors').delegate('input:checkbox', 'change', function() {
if ($(this).attr("checked")) {
var id = $("#regularCheckbox").find(':checked').val();
$('#itemMain').load('index.php?color='+id);
}
}).find('input:checkbox').change();
</script>
form:
<?php
$colors = mysql_query("SELECT DISTINCT color_base1 FROM item_descr ORDER BY color_base1");
while ($colorBoxes = mysql_fetch_array($colors))
{
echo "<input type='checkbox' id='checkbox-1-1' class='regularCheckbox' name='color' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'> ".$colorBoxes[color_base1]."</font><br />";
}
?>
</div>

$("#regularCheckbox").find(':checked')
seems to be wrong based on your PHP echo. regularCheckbox is a class, not an id, so you will want to select $(".regularCheckbox:checked'). Btw, you should not output the same id repeatedly in a loop, ids need to be unique.
Also, you might just want to use jQuery's serialize() method on your form.

Related

Grab checkbox values before form submission

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.

how to stop refreshing page on onchange="this.form.submit()"

see my client site first to get an idea.
In above site, i have a giftfinder box in right side. There are 3 select boxes. currently I'm using 3 forms for these 3 select boxes which means each drop down select box is embedded into form. When you select the first drop down select box, it picks one and second select box's value will be determined which value is selected from first select box. So if you choose Man, then all athe related occasions of Man will be dispalyed into seconds drop down select box. Its working fine.
But the problem is it refreshes everytime you select the first drop down box.
I don't want to refresh page. it must select the value and pass the value so seconds select box can determine its related values.
so I'm thinking to us ajax. but no success.
So i included some code for the first drop down select box.
this is mix of html and php and wordpress.
<div class="select-one">
<form id="searrec" method="post" action="">
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
<?php
$results_rec = get_option('current_recipient');
if(isset($_POST['selectionRecipient'])){
$results_rec = $_POST['selectionRecipient'];
update_option('current_recipient', $results_rec);
$results_rec = get_option('current_recipient');
}
?>
<?php
//asort($result_rec);
$t_name_arr = array();
foreach($result_rec as $rec):
$t_id = $rec->term_id;
$term = get_term($t_id , 'category' );
$t_name_arr[] = $term->name;
endforeach;
//print_r($t_name_arr);
rsort($t_name_arr);
foreach ($t_name_arr as $t_name):?><option class="rec_val"<?php if($results_rec==$t_name){ echo 'selected="selected"';}?>value="<?php echo $t_name;?>"><?php echo $t_name;?></option>
<?php endforeach;?>
</select>
<input type="hidden" id="submitrec" value="Search" />
</form> -->
</div>
So I'm am using form method post and using $_POST to retrieve the selected value and pass it to $results_rec variable.
Later in the code, I'm using if.. else to determine if $results_rec =='Man' then display certain items which are related to Man and so forth.
So what I want is not to refresh the page while I select item from first drop down select box.
Please help.
change this:
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
to this:
<select name="selectionRecipient" id="selectionRecipient">
and the jquery:
$("#searrec").submit(function(e) {
e.preventDefault();
// your code
return false;
});
EDITED:
use this to get the selected index (number)
var index = $("#selectionRecipient")[0].selectedIndex;
or value:
var value = $("#selectionRecipient")[0].value;
Then you can call an ajax perhaps: (assuming the other selection box has "id=other_select"
$.ajax({url:"index.php",type:"POST",data {type:"populate",index:2,value:"option1"},dataType:"json",
success: function(data) {
// data (json) returned from server so populate other selection boxes with that..
// in this example 'data' is an array, coming directly from server (see below the .php)
$("#other_select")[0].selectedIndex = 0;
for(var x in data) {
$("#other_select")[0].options[x] = new Option(data[x]);
}
}
})
in your .php i assume you get a list (etc. database) to populate the other selection list (in client). This code could looks like:
if (isset($_POST["type"]) && $_POST["type"]=="populate") {
echo json_encode(array("option1","option2","option3"));
exit(1);
}
$('#searrec').submit(function () {
//do some form submit work here
return false;
});
You'll have to use an AJAX call to populate the other select boxes based on whatever you've selected in the first one without reloading the page.
I suggest you take a look at jQuery's AJAX functionality. Read up on $.ajax and $.post - with them you could submit the value that you've selected in the first listbox to a PHP script and then based on that value return and populate the other select boxes.
Use AJAX to update the other selects without refreshing the page. Use jQuery to make AJAX easy.
This question will help:
Change the selected value of a drop-down list with jQuery
$('#searrec').submit(function(e){
e.preventDefault();
});
You should delete event onchange="this.form.submit(); from combobox
And use ajax with jquery:
$("#searrec").onchange(function() {
$.ajax({
url:"",
success:function(response){
alert("success");
}
});
});
Guys its fixed.
Plz have a look at http://giftideasitems.com/.
See gift finder box and see how it works.
I used iframe and embedded the forms, drop down coding there. thats it.
Even I used onchange="this.form.submit()" and page doesnot referesh, actually page refresh .... but not the main page, only the iframe is refreshing which is fine. this is exactly what i wanted.
<div id="gift-finder">
<div class="gift-finder-form">
<iframe name="inlineframe" src="code.php" frameborder="0"
scrolling="auto" width="200" height="180"
marginwidth="0" marginheight="0" id="gift-iframe">
</iframe>
</div>
This is my iframe code and see src, i used code.php; so all code is in separate place.
Though I had to modify some css, but anyways this is fine.
Thanks everyone who contributed yesterday.

Add to mysql with checkbox and AJAX

I have some data which will be displayed like this;
foreach ($holidays as $holiday)
{
$resultTable .= "<p>{$holiday->title}" . "<br/>" .
"{$holiday->pubDate}" . "<br>" .
"{$holiday->description}" . "<input type=\"checkbox\" name=\"saveCB\" value=\"3\"/>" . "<br /></p>";
}
Is there an easy way by which when the checkbox is clicked and the data would be added to a mysql table using AJAX?
Regards Darren
Yes you need javascript to do this. It can be done pretty easily though, if you are satisfied with the form submitting, and the page refreshing each time a select box is changed (i.e. check/unchecked). If you can't accept this, you'll have to use ajax. That would be your optimal solution, and easy as ajax is, it is a nice to have in your toolbox for future projects.
That said, you can achieve this by giving your form an id attribute, and paste this javascript just beneath your form (and edit the form id var):
<script type="text/javascript">
var formId = "YOUR FORM ID HERE";
function submitForm(){document.getElementById(formId).submit()}
</script>
Then add the following attribute to each checkbox: onchange="submitForm()".
Again, it is highly recommended to use ajax for this sort of stuff, and if you look into jQuery ajax, you'll be impressed how easy this can be done.
EDIT: What you can do to actually implement this in your existing code (replace it):
<form action="php-file-to-process-form.php" id="your-form-id" method="post">
<?php if(count($holidays)>0): foreach($holidays as $holiday): ?>
<p>
<?php echo $holiday->title; ?>
<br>
<?php echo $holiday->description; ?>
<input type="checkbox" name="saveCB[<?php echo $holiday->id; ?>]" value="<?php echo $holiday->id; ?>">
</p>
<?php endforeach; endif; ?>
</form>
<script type="text/javascript">
var formId = "your-form-id";
function submitForm(){document.getElementById(formId).submit()}
</script>
Please note i rewrote parts of your code. But in this case, assuming your $holiday objects has an "id" property, php-file-to-process-form.php should receive a fairly comprehensible post request.
PHP doesn't have onClick events, you would have to use JavaScript for something like that.. Or make it so you post your values with PHP (using a form), then it would be possible.
To avoid page refreshing with a form submit you'll want to use AJAX. You didn't tag your question as using jquery, but I highly recommend it. Here is a jQuery example of what you want:
$('input[type=checkbox]').click(function() {
if ($(this).is(':checked')) {
var name = $(this).attr('name');
var value = $(this).val();
$.post('/path/to/your/php/code', {name: value}, function(data){
//Handle the result of your POST here with data containing whatever you echo back from PHP.
});
}
});
Note that this puts the same click handler on all your checkboxes which might be the wrong assumption. If you have other checkboxes on your form that you don't want to use with this logic you'd just need to change the jQuery selector from 'input[type=checkbox]' to something more restrictive such as inputs that have a certain css class.

I need help in making my post-comment page

I need to display a comment button which toggles a div that contains the textbox and submit comment button, but the problem I am facing is that the comments div of the first post toggles properly on click but the rest don't work
My code-
$("#comment").click(function(){
var class = $(this).attr("class");
var count = $("#text").size();
$(".comments"+class).slideToggle(100);
if (count === 0) {
$(".comments").append("<br><input type='text' id='text' class='comment'/><input type='submit' value='Comment' id='login' />");
}
else{
}
});
You can only have one element with the id of comment. Try switching that to a show-comment class.
Because with $("#comment").click(function(){ ... you only pick the first element with the ID 'comment' - but i guess, you have several posts, right? :) So make it a class instead!

Focusing 'multiple' HTML input fields with jQuery or javascript

Hi again :)
I'm using jQuery script to show/hide some content:
<script type="text/javascript">
$('.toggleButton').click(function() {
var id = this.id.replace('toggleButton', '');
$('#content' + id).toggle();
});
</script>
Since I'm using PHP, I am iterating through few items and each of them has a button to show/hide its content. My content is actually a form with few input fields. In each item, first field of my form has a same name (let's say 'line1').
What I would like to do is when I click on an item and open its content, to take a focus on input field 'line1'. When I click on other item to take a focus on its 'line1' field, and so on...
Preferably with jQuery because I suppose it would be simpler, but javascript solution would be also great :)
Thanks for any help!
EDIT: I will attach a part of code which is that I need to show and hide... Maybe it will be of some help... I am using codeigniter, so not to be confused by some functions :)
echo "<div class=\"toggleButton\" id=\"toggleButton".$item['id']."\">CLICK TO OPEN</div>";
echo "<div class=\"content\" id=\"content".$item['id']."\" style=\"display:none;\">";
echo form_open('title/add'); // codeigniter's open form
for ($i = 1; $i <= $item['rows']; $i++) {
echo "<input type=\"text\" class=\"line\" id=\"line".($i)."\">".br();
}
echo form_submit('submit', 'submit'); // codeigniter's submit for button
echo "</form>";
echo "</div>";
Change your last line to:
$('#content' + id).toggle().find('input').first().focus()
did you try giving common class name and call function based on class name

Categories