How to call ajax by jquery on multiple checkboxes? - javascript

I have multiple (number may go as high as 500) checkboxes, as follows
<?php
$duplicate_checked='';
if ($repeat==1)
{
$duplicate_checked=' checked';
} else {
$duplicate_checked='';
}
?>
<input type="checkbox" name="isrepeat-<?php echo $id_no; ?>" id="isrepeat-<?php echo $id_no; ?>" class ="class_isrepeat" value="<?php echo $id_no;?>" <?php echo $duplicate_checked;?> onclick="updateRepeat(this.checked,<?php echo $id_no;?>);"/><label for="isrepeat-<?php echo $id_no; ?>">Is a duplicate Question?</label>
I want to update the value of Repeat column of the particular question number ($id_no, in this e.g.) in mysql database (e.g. named Qbank) on change of checked value of that checkbox.
I am able to successfully get checked value in javascript function updateRepeat(value, ques_no); But I couldn't get a way to call ajax by javascript.
In jquery this can be done something like -
$('#isrepeat-{question no}').change(function() {
$.post('update_repeat.php', {ques_no: question_number, repeated: checkbox_value_integer},
function(data){
$("#result").html(data);
});
});
Edit - 1. #isrepeat-{question no} represents id tag of the checkbox depending on question number eg, #isrepeat-1, #isrepeat-2, #isrepeat-3 etc.
But, This would require definite question number in "#isrepeat-{question-no}". I dont know how to construct this jquery in a way that it automatically picks question no and checked property for any particular checkbox clicked.
If I use class, instead of id for checkboxes then, how can i get question number and checkbox checked value for any checkbox in a single function?
Also, although I have a basic Idea what should be in update_repeat.php for ajax call, it would be nice if you could give any way by which this update can be easily done in ajax.
thanks.
regards,

Firstly, you are correct by utilizing class as selection to trigger the function. You can then continue by calling $(this) within the trigger callback to utilize the document object for each particular checkbox user clicked on.
Then just use .attr to get an input attribute that stores some information.
Which makes the code into
$('.class_isrepeat').change(function() {
question_number = $(this).val();
checkbox_value_integer = $(this).prop('checked');
$.post('update_repeat.php', {ques_no: question_number, repeated: checkbox_value_integer}, function(data){
$("#result").html(data);
});
});

Related

PHP keep form values when running JS script function

In a table it has a checkbox along with information in each row. When checkboxes are selected, I want it to run php related to the button and within it to call a JS function.
It calls the JS fine, but after that, it does not return to where it was and pick it up again as I still need to use the information within it when the JS has been ran. It's losing the checkboxes that were selected, and jumping out of it, whereas it's needed to keep the checkboxes selected and stay where it was.
Any help would be hugely appreciated as I've spent a long time trying different combinations to do it but not had much luck, to the point where I've even tried calling the js straight from the button and then selecting checkboxes after
'renameFile' is called from
<input type="submit" value="Rename" name="renameFile"/><br>
Then the php
if(isset($_REQUEST['renameFile']))
{
//uses checkboxes from table
if(isset($_POST['checkbox']))
{
$checkedboxes = $_POST['checkbox'];
$count = count($checkedboxes);
if($count == 1)
{
foreach($_POST['checkbox'] as $selected)
{
echo "<script> renameFile(); </script>";
if($rename = $_GET['rename'])
{
echo $rename;
}
}
JavaScript function
function renameFile()
{
var rename = prompt("Please enter a new name", "");
window.location.href="MainHomescreen.php?rename="+rename;
}

Why the JavaScript result always return first value?

here is my problem. I'm currently trying to customize joomla article content with some module. As i'm trying out hide some div before the user had click on the input. Lets say user click Test1 which is a radio button , then another field which i hide with div will shown up the content of Test1. All the detail is load from mysql database.
Here is my javascript code that i trying to show the value. But it alway show me first value although i click other value suck as Test2 or Test3.
Example:
<script type="text/javascript">
function showBox1(){
document.getElementById('hideBox1').style.display ="";
var test = document.getElementById('123').value;
confirm (test);
</script>
Here is my php code:
<?php
// Get default database object
$db =JFactory::getDBO();
// Get a new JDatabaseQuery object
$query = $db->getQuery(true);
// Build the query
$query->select($db->quoteName('campusid'));
$query->from($db->quoteName('campus'));
$query->where($db->quoteName('collegeid').'='. $db->quote('1'));
// Set the query for the DB oject to execute
$db->setQuery($query);
// Get the DB object to load the results as a list of objects
$results = $db->loadObjectList();
if($results){
foreach($results as $result)
{
echo "<label class='option block spacer-t10'>";
echo "<input type='radio' name='$result->campusid' id='123' value='$result->campusid' onClick='return showBox1()'><span class='radio'></span>";
echo $result->campusid;
echo '</label>';
}
}
else{ echo 'Error';}
?>
As an example the output for first div is 3 radio button, each radio button had it own value. When user click on either 1 of the radio button then it should pass the correct value to be shown up so that i can bring the value to the next div to select my database data. Is there any mistake i had made on my code that make me alway getting the first value although i click other radio button?
Each radio button is an element in its own right. The radio group is not a single element.
Every radio button has the same id, which is invalid and not allowed in HTML.
When you getElementById, the browser attempts to perform error recovery and gets the first element with that id (ignoring the others).
If you want to deal with a group of elements, then:
make them members of a class
getElementsByClassName
Loop over the result and test the checked property
When you find a true checked take the value of that element
Your radiobuttons have the same id 123. You are selecting the element from the DOM using this id. Make sure every radiobutton has a unique id.
You don't even need the Id if you pass the element to the function.
HTML:
onClick='return showBox1(this)'
JavaScript
function showBox1(element){
confirm (element.value);
}
First of all, all the radio buttons have the same id attributes: "123".
The document.getElementById() function expects, that a certain id is only present once on a page.
If you want to get the selected value for the elements with id "123", then you should select like this:
var test = document.querySelector("#123:checked")[0].value;
If this doesn't work, then try:
var test = document.querySelector("[id=\"123\"]:checked")[0].value;

How to access attributes of dynamically created divs using jQuery

I'm trying to retrieve a list of users from a simple MySQL database table, e.g., called TableA, which looks something like: Username(varchar), Level(tinyint), DateCreated(datetime).
On an html page I have a search input box, say - and underneath it I have a div, say to display the results. I have it so that when I start typing a word (to look for a username), jQuery makes makes an ajax request to a php file which queries the TableA for the usernames.
The jQuery part looks like:
$("#search_bar").keyup(function()
{
var user = $(this).val();
$.post('get_user.php', user_name : user, function(data)
{
$("#result_box").html();
});
}
The php script, get_user.php, again is a simple script which looks something like
<?php
$user = $_POST['user_name'];
//connect db,
$query = mysqli_query (select Username from TableA where Username like '$user%');
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div id="user_info" username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
?>
Now, previously using jQuery, every result that is being returned as a is being dumped in the result_box div ($("#result_box").html();). The problem I have with this is that if I have 3 users, say Mick, Mike and Mila and I start searching by typing 'M', the query returns all three (that's fine), however, when I click on a name, say the last one returned would be Mila, this will trigger another jQuery function which say for now just prints the name of the selected in a popup box - it however picks up the attribute of the first name, Mick, from the the first div that appeared there and not the one I clicked on. It's strange. If the search returns only a single entry then that's fine - however with multiple entries, regardless of which one I click, jQuery picks up only the first one.
I suspect its because the divs all have the same ID, and since they are being 'dynamically' created - jQuery just picks up the attribute (e.g., $("#user_info").attr('username') ) of the very first one or only one created?
Any help would be appreciated.
Thanks
You should use jQuery data()
You should create the div like :
<div class="userLink" data-username="$row['username']"></div>
And acces it from jQuery like
$('.userLink').on('click',function(e) {
var username = $(this).data('username');
}
And the attribute ID must be UNIQUE.
First off, you need to fix the issue of multiple DOM objects with the same id. Perhaps you can just use a class name. But, that probably won't fix your click issue. The click issue should be fixed by using the this reference that comes with the click event. This will tell you exactly which items was clicked on so even if there are multiple items, you can know which one was clicked on and can reference the attributes on that particular object with code like this:
$(this).attr("username");
FYI, you perhaps should use the HTML5 convention of data attributes. So, instead of an attribute of username="xxx", you would use data-username="xxx". Then, you can use:
$(this).data("username");
You can combine all these changes with delegated event handling to have a click handler like this:
Your PHP (switch to a class name and data-username attribute):
//IMPORTANT PART HERE, I create a <DIV> or can be <P> and display it back
while ($row = mysqli_fetch_array($query))
{
echo "<div class="userInfo" data-username='".$row['Username']."'>".$row['Username']."</div>
//I have the username as an attribute so I can make another .post request and get detailed user info.
}
Your delegated event handling click handler in the page:
$("#result_box").on("click", ".userInfo", function(e) {
var username = $(this).data("username");
});

JavaScript variable passed to PHP

I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];

Can't get form's select element value using jQuery

I am able to get input element's value using
var flt=$("#flt"+rowID).val();
but cannot get select elements value
here is my php code
<?php
$AC= & getAC();
while ($rowAC=mysql_fetch_array($AC)){
$i++;
if ($rowAC['acode']==$row['TPE']){
echo "<option value='{$rowAC['acode']}' selected='selected'>{$rowAC['name_ru']}</option>";
}else{
echo "<option value='{$rowAC['acode']}'>{$rowAC['name_ru']}</option>";
}
}
?>
I am generating list using this php code but
cannot even getting it's text value coding in such a way
var tpe=$("#tpe option[value='2']").text();
window.alert(tpe);
I am concerned only to get it's option value!!!
How to get it???
After some quick testing, it appears that value() only works on the select element itself. To get the value of the different option elements, you can use attr('value') on the option elements themselves.
Very quick demo: http://jsfiddle.net/y9Dqg/2/

Categories