What I have here is a table that displays record from my database. It also generates dynamic checkboxes along with the fetched record. What I need to do is to open a new window using window.open, instead for the page to go to editor.php. Any help will be gladly appreciated.
MySQLi Query
while ($row = $result1->fetch_assoc()) {
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="' . $row['id'] . '"'.($row['pr'] == ""?"disabled ":"").' style="cursor:pointer;" class="checkbox"></td>
}
Javascript
<script type="text/javascript" language="javascript">
function setCheckboxes3(act) {
$('.checkbox').not(':disabled').prop('checked', act == 1 ? true : false);
//or $('.checkbox:not(:disabled)').prop('checked', act == 1 ? true : false)
}
</script>
<script>
jQuery(function ($) {
$('a.button.edit, a.button.remove').click(function () {
if ($('input[name="checkbox[]"]:checked').length == 0) {
return;
}
if ($(this).hasClass('edit')) {
if (!confirm('Edit this Record(s)?')) {
return
}
} else {
if (!confirm('WARNING !!! All Purchase Order that included in this Record(s) will be deleted.')) {
return
}
}
var frm = document.myform;
if ($(this).hasClass('edit')) {
frm.action = 'editpr.php';
}
if ($(this).hasClass('remove')) {
if (!confirm('Are you sure want to continue?')) {
return
}
}
frm.submit();
})
})
</script>
HTML
<a class="button edit" style="cursor:pointer;"><span><b>Edit</b></span></a>
Related
I have the code below and this code works, but only after clicking on selection option but code doesn't work when i change value when use arrow up and down.
I tried modification script, change option "click" to "change" but this solution doesn't work. Someone can help me ?
$select = $db_connect -> query("SELECT * FROM templates");
if($select -> num_rows > 0)
{
echo '<select id="subject" name="subject" class="form-select">';
while($row = $select -> fetch_assoc())
{
echo '<option id="'.$row["id"].'" value="'.$row['template_subject'].'">'.$row['template_subject'].'</option>';
?>
<script>
$("#subject #<?php echo $row['id']; ?>").on('click', function(){
if((this.id = "<?php echo $row['id'];?>") && (this.id != 1))
{
$("textarea").html("<?php echo $row['template_text']; ?>");
$("input[name='new_subject']").hide();
}
else
{
$("textarea").html("");
$("input[name='new_subject']").show();
}
});
</script>
<?php
}
echo '</select>';
}
Your problem is in the Javascript code.
<script>
$("#subject").change( function(){
var text = $( "#subject option:selected").val();
var id = $(this).children(":selected").attr("id");
if(id != 1)
{
$("textarea").html(text);
$("input[name='new_subject']").hide();
}
else
{
$("textarea").html("");
$("input[name='new_subject']").show();
}
});
</script>
remove the script from the while loop , put it at the end before </body> tag.
I have a page with 2 select boxes, one of which is loaded by an AJAX call. I then want to validate the elements with jquery before I enable the submit button. The jquery works fine when I change the static select (strDirectorate) but not when I change the one loaded by AJAX (new_cc).
Is it because jquery is getting the value of new_cc as it was when the page was loaded?
<div class="selectfield">
<select id="strDirectorate" name="strDirectorate" class="mainform_select" onChange="getNewCostCentre(this.value)">
<option value="" selected="selected"></option>
<?php do { ?>
<option value="<?php echo $row_rsLocality['strLocalityShort']?>" <?php if($row_rsLocality['strLocalityShort'] == $strDirectorate){ echo $selected; } ?>><?php echo $row_rsLocality['strLocalityLong']?></option>
<?php
} while ($row_rsLocality = mysql_fetch_assoc($rsLocality));
$rows = mysql_num_rows($rsLocality);
if($rows > 0) {
mysql_data_seek($rsLocality, 0);
$row_rsLocality = mysql_fetch_assoc($rsLocality);
}
?>
</select>
</div>
<div id="txtNewCostCentre" class="selectfield">
<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">
<option value="" selected="selected"></option>
</select>
</div>
<div class="actions">
<input type="submit" id="submit_button" name="submit_button" class="styled_button" value="Submit" />
</div>
The function getNewCostCentre is
function getNewCostCentre(str)
{
if (str=="")
{
document.getElementById("txtNewCostCentre").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getNewCostCentre.php?q="+str,true);
xmlhttp.send();
}
The code for getNewCostCentre.php is
$sql="SELECT * FROM `tblcostcentreorganisation` WHERE `strOrganisation` LIKE '363 ".addslashes($dir)."%'";
$result = mysql_query($sql);
if(isset($_GET["q"])){
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)" style="background-color:#F8E0E0">';
$display_string .= '<option value="" selected="selected" disabled="disabled"></option>';
}else{
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">';
}
while($row = mysql_fetch_array($result))
{
$cc = substr($row['strCostCentre'], 3, strlen($row['strCostCentre'])-3) . " " . substr($row['strOrganisation'], 3, strlen($row['strOrganisation'])-3);
$org_name = $row['strOrganisation'];
if ($org == $org_name){
$display_string .= '<option value="'.$org_name.'" selected="selected">'.$cc.'</option>';
}else{
$display_string .= '<option value="'.$org_name.'">'.$cc.'</option>';
}
}
$display_string .= '</select>';
echo $display_string;
And the jquery validation is:
$(document).ready(function() {
$('.selectfield select').change(function() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
});
});
The onload code is as follows. I assume it's because I'm using .load within (after) .onload?
$(document).ready(function(){
window.onload = function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded);
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
});
You are binding your change handler for $('.selectfield select') when the page loads. This attaches the handler to all elements that match that selector.
If you then change this element, it won't have the handler attached.
Instead, you should use the live handler, to match all elements that exist now or are ever created in the future.
$('.selectfield select').live("change", function() {
...
});
UPDATE:
For you onload issue, it would be far easier not to repeat your code. If you need to fire off the validation after loading the content dynamically, then trigger the change event once the load has finished - like the following example:
$(document).ready(function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded, function() {
$('.selectfield select').trigger("change");
});
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
});
An ajax update of the input shouldn't trigger the javascript change event so the handler you've specified in change won't get called.
From the javascript specification (http://www.w3.org/TR/html401/interact/scripts.html) :
onchange = script [CT] The onchange event occurs when a control loses
the input focus and its value has been modified since gaining focus.
This attribute applies to the following elements: INPUT, SELECT, and
TEXTAREA.
I'd suggest performing the validation logic in the same part of your javascript where you're handling the response from the ajax request. Right after the line
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
add the call
validate();
Where validate is earlier defined as :
function validate() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
So that your jquery validation becomes:
$(document).ready(function() {
$('.selectfield select').change(validate());
I need help on making a delete confirmation that need a minimum of 1 record to be deleted.
I'm still confused on making it. I think there's something wrong in my javascript code. Any help would much be appreciated. Thanks
here's the php code:
enter code here
<script src="javascript.js" type="text/javascript"></script>
<?php
echo"<form method=POST action='action.php?act=delete'>
<input type=checkbox name='checkbox[]' value='1'>1
<input type=checkbox name='checkbox[]' value='2'>2
<input type=checkbox name='checkbox[]' value='3'>3
<input type=submit value=Delete onClick='return del_confirm();'></form>";
?>
here's the javascript code:
enter code here
function del_confirm()
{
var msg=confirm('Are you sure?');
var c=document.getElementsByName('checkbox[]');
if(msg)
{
for(i=0;i<c.length;i++)
{
if(c[i].checked)
{
return true;
}
else
{
alert("Select minimum of 1 record to be deleted!");
return false;
}
}
}
else
{return false;}
}
Your logic is a bit off:
function del_confirm() {
var msg = confirm('Are you sure?');
var c = document.getElementsByName('checkbox[]');
if(msg) {
for(i = 0; i < c.length; i++) {
if(c[i].checked) {
return true;
}
}
// This has to be outside the for loop,
// that way it only gets here if every box is not checked
alert("Select minimum of 1 record to be deleted!");
return false;
} else {
return false;
}
}
You had the alert inside the for loop so the first unchecked box returned false for the function.
Example Fiddle: http://jsfiddle.net/FfkvW/
I know this is a very basic question, but i couldnt figure how to fix the code even after crawling the web for past 1 hour.
I have an unordered list containing the information about the categories in the database, with cat_id as primary key. and a subject table with cat_id as its foreign key, so i want to access the subjects table through ajax request for given category ID. below is the code i used to generate categories. Where i am stuck is, i dont know which DOM element to fetch in order to send the unique id in the url parameter ..
thanks ..
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li id="';
echo $category->cat_id;
echo '"><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
<div id="results">
<!-- ajax contents goes here -->
</div>
the ajax file is
window.onload = init;
function init() {
if (ajax) {
if (document.getElementById('results')) {
document.getElementById('search_form').onclick = function() {
ajax.open('get', 'subject.php?id='+id ); // subject.php?id=
// how will i pass the variable
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
}
}
function handleResponse(ajax) {
if (ajax.readyState == 4) {
if ((ajax.status == 200) || (ajax.status == 304) ) {
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
results.style.display = 'block';
}
}
}
and the subject.php
<?php
//include("tpl/header.php");
include("includes/initialize.php");
?>
<h2></h2>
<?php
if (isset($_GET['id'])) {
$id= mysql_real_escape_string($_GET['id']);
$subject = Subject::find_subject_for_category($id);
foreach($subject as $subj) {
echo $subj->subject_title;
}
} else {
echo "No ID Provided";
}
?>
I have used Jquery to do these kind of things and it works fine for me.
$.ajax({
type: GET,
url: "subject.php",
data: {id: $('#search_form :selected').val()},
success: function(result){
// callback function
}
});
This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.
The problem is, if the last 'if' is not met, then the 'else' will fire.
This means as long as a valid email address is entered the form will submit, even if other fields are blank.
How can I make so that all requirements must be met for the form to submit
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
else {
//submits to database...
}
You can use a flag as:
$isValid = true;
if(empty($_POST['company'])) {
$isValid = false;
// your echo
}
Similarly add the $isValid = false; for all the other if bodies.
Finally remove your else part and replace it with:
if($isValid) {
// submit to DB.
}
you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation.
like so:
if() {
} elseif() {
} else {
...
}
or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...
<?php
$error = 1;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if($error == 1) { //submits to database...
}
?>
There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.
// loop through all submitted fields
foreach( $_POST as $key => $value){
// see if the field is blank
if($value=="" || $value is null){
// if blank output highlighting JS
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
// variable to value showing form is invalid in some way
$invalid=1;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$invalid= 1;
}
// if form invalid variable not set, submit to DB
if($invalid!=1){
// submit to DB
}
If you want to be super efficient you can simply use:
// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");
// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
foreach( $invalid_fields as $key => $value){
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
}
$error = 1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 1;
}
if($error!=1){
// submit to DB
}
Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false.
Then rewrite the else-Part and do a
if ($sendToDb) {
/* Your Db-Write code */
}
Take a flag variable and check like this
$flag=0;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if ($flag == 0)
{//submit to database
}
You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).
Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:
<?php
if (isset($_POST['submit'])) {
$errors = array();
// do server-side validation
if ($_POST['fieldName'] == '') {
$errors['fieldName'] = 'fieldName is required';
}
if (count($errors) == 0) {
// save your record to the database or whatever
}
}
And then the following template:
<style>
.error { border-color: red; }
</style>
<script>
$(document).ready(function() {
$('form#yourFormId').submit(function() {
var errors = null;
if (errors.length > 0) {
return false;
}
});
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
<input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
<input type="submit" name="submit">
</form>
This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.