Following is an ajax post page which renders the checkboxes on run-time. I am facing issue while writting the script for select all button, when I click on the button only 1 value is getting selected not the entire array:
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("../includes/functions.php");
if(isset($_REQUEST['t']))
{
$td = $_REQUEST['t'];
$t = split(",",$td);
$all = "";
$box_in_row = 0 ;
$this_box="<table border=0><tr>";
foreach($t as $table)
{
$this_box = "<td><h3>$table</h3>";
$result = mysql_query("SHOW FULL COLUMNS FROM $table FROM prfxcom1_prfx");
$options = "";
while($r = mysql_fetch_object($result))
{
if(!empty($r->Comment))
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
}
}
if($table == "transfer_req")
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='Net Profit' id=\"$table\">NetProfit";
}
$this_box .= $options;
// Button
$click = "$('#$table').attr('checked', 'checked')";
$button = "<br /><input style='margin-top:10px;' type='button' name='$table_button' id='$table_button' value=' Select All ' onclick=\"$click\"/>";
$all .= "<div class='tblBox'>".$this_box.$button."</div></td>";
}
//$all = "<table class=\"listing form\" cellpadding=\"0\" cellspacing=\"0\">".$all."</table>";
echo $all;
}
?>
Issue is faced in the line:
$click = "$('#$table').attr('checked', 'checked')";
Please suggest, I am stuck on this.
Thanks,
Hardik
WHAT???
$click = "$('#$table').attr('checked', 'checked')";
How can you write Javascript in the middle of a PHP file? It needs to be in script tags but even then PHP runs at the server and will not render your Javascript for you.
Add script tags, change your ID's to separate ones and give them the same class like tableClassName, and then write the following.
$(function(){
$('.tableClassName').attr('checked', 'checked')";
});
Ignoring the many issues with the code and simply answering the question:
You need to refer to the checkboxes using a class name not a ID (you have given them all the same ID)
For these lines: $options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
Change to: $options .= "<br><input type=checkbox name='" . $table . "[]' value='" . $r->Field ."' class='" . $table . "'>" . $r->Field;
For this line: $click = "$('#$table').attr('checked', 'checked')"; use single quotes or escape the $
Change to: $click = '$("."'.$table.'").attr("checked", "checked")';
Related
I am trying to use jQuery to change the background color of the select element based on the option chosen within.
To generate the select elements, I'm using the following code:
while ($qrow = $qquery->fetch(PDO::FETCH_ASSOC)) {
$aqanswer = "qAnswer" . $qrow['questionID'] . "";
$aqcomments = "qComments" . $qrow['questionID'] . "";
echo "<tr><td class='auditf'>" . $qrow['qDesc'] . "</td><td class='auditm'><select name='qAnswer" . $qrow['questionID'] . "' form='entryform' id = 'selectqAnswer". $qrow['questionID'] ."'>";
if (isset($_SESSION[$aqanswer])) {
if ($_SESSION[$aqanswer] === 'Green') {
echo "<option value='Green' selected='true' class = 'green'>Green</option>";
echo "<option value='Red' class='red'>Red</option>";
} elseif ($_SESSION[$aqanswer] === 'Red') {
echo "<option value='Green' class ='green'>Green</option>";
echo "<option value='Red' selected='true' class = 'red'>Red</option>";
}
unset($_SESSION[$aqanswer]);
} else {
echo "<option value='Green' selected='true' class = 'green'>Green</option>";
echo "<option value='Red' class = 'red'>Red</option>";
}
echo "</select></td><td class='auditl'><textarea name='qComments" . $qrow['questionID'] . "' rows='3' cols='30' maxlength='255' value='N/A'>";
if (isset($_SESSION[$aqcomments])) {
echo $_SESSION[$aqcomments];
unset($_SESSION[$aqcomments]);
} else {
}
echo "</textarea></td></tr>";
}
And my jQuery:
$("[id^=selectqAnswer]").change(function () {
var color = $("option:selected", this).attr("class");
$("[id^=selectqAnswer]").attr("class", color);
});
Now this does work, but it causes every single box on the page to change, obviously. The problem is, the number of boxes on the page can change based on user options, so I don't have a fixed list of select IDs that I could reference individually in my jQuery. I've tried Googling the issue, but every single result talks about specifically naming the ID, not working with an ID that's generated procedurally. How do I only change a specific select element's background color based on the select option selected when I don't know what the ID will specifically be ahead of time.
$("[id^=selectqAnswer]").attr("class", color);
this will change the color for every #selectqAnswer select, if you want to change the color of the current select use this
Javascript
$(this).attr("class", color);
I am trying to set condition user select at least one language on page here is my jQuery code
$(".a_orignal").click(function(){
var checked = $(".a_orignal input:checked").length > 0;
if (!checked){
alert('You can select at least one Languages!!');
return false;
}
});
and my php code is :
print "<div id='outer_menu'>";
$value1_node = ($content['field_translation']['#items'][0]['value']);
$value2_node = ($content['field_translation']['#items'][1]['value']);
$lang=db_query("SELECT name FROM field_revision_field_language, taxonomy_term_data
WHERE entity_id = $value1_node
AND field_language_tid = tid
")->FetchField();
print "<input type='checkbox' name='mychoice' value=" . $lang . " class='a_orignal' checked />";
print "<label for name=" . $lang . ">" . $lang . "</label>";
$lang1=db_query("SELECT name FROM field_revision_field_language, taxonomy_term_data WHERE entity_id = $value2_node AND field_language_tid = tid")->FetchField();
print "<div id='b'>";
print "<input type='checkbox' name='mychoice' value=" . $lang1 . " class='a' />"; print "<label for name=" .$lang1 . ">" . $lang1 . "</label>";
print "</div>";
print "</div>";
When I click on last check box they alert me but value of check is hidden they are not shown.
you can try this $('.a_orignal:checked').size() then checked if the size is greater than 0 or not
Do not use click event listeners on checkboxes - it could fire earlier than the change event.
Play with this sample:
$(".a_orignal").change(function(){
//your change handler here
});
Use on event instead of click event. Try following code:
$(".a_orignal").on( "click", function(){
var checked = $(".a_orignal input:checked").length;
if (!checked){
alert('You can select at least one Languages!!');
return false;
}
});
I´m stuck for 3 days trying to figure it out what is the cause of this problem. Lets go to the details:
A jquery ajax call loads a php file named HELPER, wich when loaded includes another php file called F1 that creates html table trough mysqli queries. Ajax get the response and paste the string in a html DIV. The response is a html table. The web server is apache2.2.
Problem is, the code runs in less than 1 second, but the response takes about 50 seconds. The response is only 20 KB.
Some simple HTML table code.
<?php
if (!$res = $sql->query("A QUERY")) { die('custom error 46'); }
if (!$res->num_rows > 0) { die('custom error 47'); }
$myStr = '';
while ( $row = $res->fetch_object() ) {
if ($row->summary == "1") {
$mysum = " class='qtfck-table-summary'";
$myIsSum = "Sim";
} else {
$mysum = "";
$myIsSum = "";
}
if(intval($row->id_centrodecusto) > 0) {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='" . $row->id_centrodecusto . "' CHECKED />";
} else {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='' />";
}
$myj = " style='padding-left:" . intval($row->depth) * 10 . "px'";
$myStr = "<tr%s><td>%s</td><td><center>%s</center></td><td><center>%s</center></td><td%s>%s</td><td><center>%s</center></td><td><center>%s</center></td></tr>";
echo sprintf($myStr,$mysum,$row->wbs,$row->depth,$myIsSum,$myj,$row->name,$row->uniqueid,$mycc);
}
?>
Html Table closure
The timmings:
PHP START: 0.92 sec
PHP END: 0.98 sec
JS RECEIVED DATA: 49.50 sec
JS PROCESSED DATA: 49.56 sec
I did some digging and it looks like the apache/httpd process (shell via top command) is going nuts, taking 100% CPU load during the full 50 seconds of wait.
BUT here´s something funny. If I change the string generated by the sprintf function and, let´s say, set some random string, there´s no problem at all.
Some simple HTML table code.
<?php
if (!$res = $sql->query("A QUERY")) { die('custom error 46'); }
if (!$res->num_rows > 0) { die('custom error 47'); }
$myStr = '';
while ( $row = $res->fetch_object() ) {
if ($row->summary == "1") {
$mysum = " class='qtfck-table-summary'";
$myIsSum = "Sim";
} else {
$mysum = "";
$myIsSum = "";
}
if(intval($row->id_centrodecusto) > 0) {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='" . $row->id_centrodecusto . "' CHECKED />";
} else {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='' />";
}
$myj = " style='padding-left:" . intval($row->depth) * 10 . "px'";
echo "<TR><TD>eZ6OnMCZgygePZeUQHcqbOmHQDxhDF4KzfkgOd198xhPFV2rRezlIqBdJLY2TcNlO0PLUmK6CQI9PQMZgkLrcoeYIYhM0x9xK4yQXIFb5SLdq32</TD><TD>UTuQPG9WCbOswuJMdkkckMoAW49C71IN9qKdk8OAdRRV3ZuCYxM5GEZKrXXrwE7cWHKTcXTiO4KwGjh1ejENvduZvEVkwA3zoHbWkzEjtFa1GMaNzD2rqswEDSoQix2CLziBNiHD8zliSWu5rvU8wd6dodWBvubvog</TD></TR>";
}
?>
Html Table closure
The response to this request is 50 KB in size.
The timmings:
PHP START: 0.78 sec
PHP END: 0.81 sec
JS RECEIVED DATA: 1.13 sec
JS PROCESSED DATA: 1.19 sec
What I have already tried:
Use ob_start() and ob_end_flush().
Set apache mpm prefork SendBufferSize to a higher value, but I believe it was a long shot, as the longer response (50KB) has no problem.
Use echo instead of sprintf.
Anyone has a clue?
Best regards.
I don´t know why but the problem was caused by the "center" html tags. Somehow the presence of the center tags slowdown the response. I just removed them and created appropriate css classes using "text-align: center" and the problem was gone.
I also did try avoiding PHP to echo the HTML. Even then the tags causes problems again.
Here´s the fix. I just don´t have an explanation for it.
My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']
Once it loads in my page, if nothing has been saved in the DB table, all options are shown. As soon as i make a selection and reload the page, the selected option dissapears from the list and isn`t reloaded in the dropdown. Instead, it displays the next value which takes the place of the selected one.
if i check the SQL statement and the $str, it does load all the options except the one which is selected which is in $getBris (it has a value).
What could be causing my select to not display my selected option and instead removing it from the list?
*It specifically doesnt work in IE8, wasnt working in Firefox but now it does
<script src="validation.js" type="text/javascript"></script>
<html>
<body onLoad="checkSecondValue();">
</body>
</html>
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
// ORDER BY RAND()
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$getBris = $_GET['bris'];
$getBris = $getBris - 1;
print_r("bris is : "+ $getBris);
if($getBris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value='999'>Choisir un bris</option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $getBris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
$i++;
}
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
echo "<script type=\"text/javascript\">alert('test');checkSecondValue();</script>";
}
?>
Use your browser's View Source feature to inspect the actual HTML you are generating (which is, in fact, the only see the browser ever sees). It looks like you're inserting random single quotes.
Update:
<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>"
... will render as:
<option value='blah' selected '>blah</option>
It's the only error I've cared to spot but an HTML validator should find them all. Also, I recommend you use this syntax:
<option value="blah" selected="selected">blah</option>
A construct like this
if($getBris == 12)
{
$str .= "<option value=12 selected>Autre</option>";
}
else
{
$str .= "<option value=12>Autre</option>";
}
is highly wasteful of space and forces you to duplicate a big chunk of html whose only difference is the "selected" attribute. Why not do something like this:
$selected = ($getBris == 12) ? ' selected' : '';
$str .= "<option value=12{$selected}>Autre</option>";