The design of my page has a form comprising a textbox at the top contained in a div element. Beneath that I have datatable with a checkbox in each row of the table. This entire form is in turn contained in another div element around it.
In this case, whenever I submit the form with some value in the textbox above and selecting one of the rows by checking the checkbox, the checkbox value is not getting passed through the form submission.
If I remove the div element around the textbox above and put the entire form
in a single big div, it works. However, I have constraint here that I can not
remove the inner div containing the textbox. I can not explain why I have such constraint since this is just a simplified and to-the-point version of my requirement.
I am also including the CGI Perl code along with a runnable code below, in the form action just the current script only needs to be called :
enter code here
use CGI;
use CGI::Carp qw(fatalsToBrowser);
my $qry = new CGI;
&main();
sub main {
$qry->header();
my $body = &display_page();
print $body;
}
sub display_page {
my $url = "current_script.cgi";
print '<pre>' . Data::Dumper::Dumper( \%{$qry->Vars}) . '</pre>';
my $checked1 = "checked" if defined $qry->param('First') || '' ;
my $checked2 = "checked" if defined $qry->param('Second') || '' ;
my $checked3 = "checked" if defined $qry->param('Third') || '' ;
my $html .= qq{<br>
<div>
<div>
<form name='myForm' action='$url' method=post>\n};
$html .= $qry->textfield(-name=>'TEXT_FIELD',
-default=>'Enter your text here',
-size=>35,
-maxlength=>50);
$html .= "<br><br> </div>";
$html .= qq{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<link rel='stylesheet' type='text/css' href='https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css'>
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script src ="/js/testchkbox.js"></script>
};
$html .= qq{
<table width = "90%" border="1" >
<tr>
<td>
<div class="container" >
<table id = "test" class="display compact cell-border table-bordered stripe row-border order-column" width="100%">
<thead>
<tr bgcolor="skyblue">
<td>Check</td>
<td>Name</td>
<td>DOB</td>
<td>Address</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name = "Second" value = "1st" $checked1></td>
<td>Mark</td>
<td>11-22-15</td>
<td>London-101</td>
</tr>
<tr>
<td><input type="checkbox" name = "Second" value = "2nd" $checked2 ></td>
<td>Sam</td>
<td>11-22-15</td>
<td>London-101</td>
</tr>
<tr>
<td><input type="checkbox" name = "Second" value = "3rd" $checked3></td>
<td>John</td>
<td>11-22-15</td>
<td>London-101</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</table>
};
$html .= <<END;
#{[ $qry->submit(-name=>'STORE', -value=>'Submit') ]}
END
$html .= "</form><br></div>";
return $html;
}
https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js
$(document).ready(function(){
var table = $('#test').DataTable({
bInfo: true,
bSort: true,
bFilter: true,
scrollX: '100%',
scrollY: '475px',
paginate: false,
scrollCollapse: true,
dom: '<"toolbar">frtip',
oLanguage: {
"sSearch": "Search"
},
});
/* client side csv export button */
new $.fn.dataTable.Buttons(table, {
buttons: [{
extend: 'csvHtml5',
text: 'Export',
className: 'export btn btn-sm btn-success'
}]
});
/* add the button to the div with class name toolbar */
table.buttons().container().find("a").removeClass( 'btn-default' );
table.buttons().container().appendTo( $('div.toolbar') );
/* use the below button in case we need to fetch the data from server side */
/*
var bootstrapButton = "title='Export data into CSV' class='export btn btn-sm btn-success' role='button'"
$("div.toolbar").html("Export");
*/
});
https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css
<pre>$VAR1 = {};
</pre><br>
<div>
<div>
<form name='myForm' action='current_script.cgi' method=post>
<input type="text" name="TEXT_FIELD" value="Enter your text here" size="35" maxlength="50" /><br><br> </div>
<table width = "90%" border="1" >
<tr>
<td>
<div class="container" >
<table id = "test" class="display compact cell-border table-bordered stripe row-border order-column" width="100%">
<thead>
<tr bgcolor="skyblue">
<td>Check</td>
<td>Name</td>
<td>DOB</td>
<td>Address</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name = "Second" value = "1st" ></td>
<td>Mark</td>
<td>11-22-15</td>
<td>London-101</td>
</tr>
<tr>
<td><input type="checkbox" name = "Second" value = "2nd" ></td>
<td>Sam</td>
<td>11-22-15</td>
<td>London-101</td>
</tr>
<tr>
<td><input type="checkbox" name = "Second" value = "3rd" ></td>
<td>John</td>
<td>11-22-15</td>
<td>London-101</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</table>
<input type="submit" name="STORE" value="Submit" />
</form><br></div>
You can't write your html like this:
<div>
<form name='myForm' action='current_script.cgi' method=post>
<input type="text" name="TEXT_FIELD" value="Enter your text here" size="35" maxlength="50" /><br><br>
</div>
This breaks the code. Your browser doesn't really know where the form ends and therefore the checkboxes don't get submitted.
If you need a div around your "textbox", put it around your "textbox" like this:
<div>
<input type="text" name="TEXT_FIELD" value="Enter your text here" size="35" maxlength="50" /><br><br>
</div>
In general check your html for syntax errors (https://validator.w3.org/).
Related
I'm trying to change background color of some rows in table, when input of row is >=1000 and I click the button. I'm doing it with inputs in table and submit button. In php I'm making variable int from input and in JS checking if it is <=1000 and changing background color. But it is just for a moment, after that page is refreshing, shouldn't be. Here's my code:
<form action="" method="post">
<table>
<thead>
<tr>
<th>first</th> <th>second</th> <th>third</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td>1</td> <td><input type="text" name="value11" /></td><td><input type="text" name="value12" /></td>
</tr>
<tr id="2">
<td>2</td> <td><input type="text" name="value21" /></td><td><input type="text" name="value22" /></td>
</tr>
</tbody>
<?php
if(isset($_POST['green'])){
$value21 = (int)trim($_POST['value11']);
$value21 = (int)trim($_POST['value21']);}
?>
</table>
<button type="submit" name="green" onclick="makeGreen()">button</button>
</form>
<script>
function makeGreen() {
var val1 = "<?php echo json_encode($value11) ?>";
var val2 = "<?php echo json_encode($value21) ?>";
if(val1 >= 1000)
document.getElementById("1").style.backgroundColor = "green";
if(val2 >= 1000)
document.getElementById("2").style.backgroundColor = "green";
}
</script>
Can You tell me what is wrong? Why it is not working?
When the button is hit, you're actually calling the function makeGreen(), then your form is submitted.
If you only want to make the background row green by hitting the button, you should replace the submit type by a button one, try this :
<button type="button" name="green" onclick="makeGreen()">button</button>
I am trying to autopopulate an input field (location-name) with the value entered in another field (location-address). I have looked online everywhere and managed to make the JS snippet work on a straightforward example, but for some reason this is not working with the following php code.
Just to clarify, I would like the value entered in "location-address to be passed to "location-name".
<script>
$('#location-address')
.keyup(function() {
var value = $(this).val();
$('#location-name').text(value);
})
.keyup();
</script>
<tr class="em-location-data-name">
<th style="padding-top: 14px;">
<?php _e ( 'Event unique identifier:', 'dbem' )?>
</th>
<td>
<input id="location-name" type="text" name="location_name" />
</td>
</tr>
<tr class="em-location-data-address">
<th style="padding-top: 14px;">
<?php _e ( 'Address:', 'dbem' )?> </th>
<td>
<input id="location-address" type="text" name="location_address" value="<?php echo esc_attr($EM_Location->location_address, ENT_QUOTES); ; ?>" />
</td>
</tr>
Firstly your code needs to be placed in a document.ready handler. Secondly, you need to use val() not text() to set the value of an input field.
$(function() {
$('#location-address').keyup(function() {
var value = $(this).val();
$('#location-name').val(value);
}).keyup();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="em-location-data-name">
<th style="padding-top: 14px;">
<?php _e ( 'Event unique identifier:', 'dbem' )?>
</th>
<td>
<input id="location-name" type="text" name="location_name" />
</td>
</tr>
<tr class="em-location-data-address">
<th style="padding-top: 14px;">
<? php _e( 'Address:', 'dbem') ?>
</th>
<td>
<input id="location-address" type="text" name="location_address" value="<?php echo esc_attr($EM_Location->location_address, ENT_QUOTES); ; ?>" />
</td>
</tr>
</table>
You need to wrap your jQuery code in $(document).ready(); so that jQuery binds all HTML elements.
Corrected code:
<script>
$(document).ready(function(){
$('#location-address').keyup(function() {
var value = $(this).val();
$('#location-name').val( value );
});
}).keyup();
</script>
Use this
<script>
$(document).ready(function(){
$('#location-address').keyup(function() {
var value = $(this).val();
$('#location-name').val( value );
});
});
</script>
Trying to self create a validation that compares Gross and Tare values in the table using jQuery validation plugin. Tare should always be smaller than Gross.
Here is the JS code:
$.validator.addMethod('lessThan', function (value, element, param) {
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({rules: {tare: {lessThan: ".gross"}}});
And my HTML:
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
</tbody>
</table>
</form>
This code works fine when only have one row involved.
When comes two table rows, it compares the 2nd row tare value with the 1st row gross value. Apparently I want it to compare 2nd row tare value with 2nd row gross value. Also for some reason the error message shows up at the 1st row.
Here is one screen shot:
Please advise how do I change my code to make it working properly.
And here is the CDN that I am using:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
Looking for $('.gross').val() will always retrieve the value of the first matched element (in the whole document).
Instead, look only in the row containing the element being validated:
var j = parseInt($(element).closest('tr').find(param).val());
$.validator.addMethod('lessThan', function(value, element, param) {
console.log(element);
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(element).closest('tr').find(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({
rules: {
tare: {
lessThan: ".gross"
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
</tbody>
</table>
</form>
I found a tutorial that auto submits the form data but all I want to do is add a submit button to pass the data to ajax.
My goal is to have a form with multiple inputs and when the user clicks the submit button it sends it through ajax and updates the page without reloading the page. Also, another key piece is the way it post all the inputs into an array so that when the update script is ran the name attributes from the input fields match the columns in the database.
I think I'm close. I've searched and haven't found my exact solution. Thanks in advance.
<script type="text/javascript" src="/js/update.js"></script>
<form method="POST" action="#" id="myform">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
<div id="alert">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event) {
updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
$('#alert').text('Updated');
$('#alert').fadeOut().fadeIn();
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
// FORM: Variables were posted
if (count($_POST))
{
$data=unserialize($_POST['data']);
// Prepare form variables for database
foreach($data as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$column."='".$value."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
Ended up figuring it out. Thanks for everyones help.
<p id="alert"></p>
<form id="form" method="post" action="/ajax/update_company_info.php">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<input type="submit" value="Save" id="submit">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var value = input.val();
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
//var method = form.attr('method');
//var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
$.ajax({
url: "/ajax/update_company_info.php",
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
type: "POST",
success: function(data) {
$('#alert').html("<p>Sent Successfully!</p>");
}
}); // end post
});// end each input value
}); // end submit
}); // end ready
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
function clean($value)
{
return mysql_real_escape_string($value);
}
// FORM: Variables were posted
if (count($_POST))
{
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
I think that you want to update form when submit.so you should
remove submit with a button given below.
<button id="myBtn">Save</button>.
You should add the given below code in ur js file.
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event){
Updateform('give id of the form');
});
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
});
You can retrieve input value in your php code by using unserialize()
as an array.So you can save data to
database and whatever you want to.i hope you get the answer.Hence,your code will become
<form method="POST" action="#" id="form1">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
</td>
<td></td> </tr> </table> <!-- end id-form --> </form>
Your js code become
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event)
{ Updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_company_info.php will become
$data=unserialize($_POST['data']);
// you can retrieve all values from data array and save all .
?>
Instead of:
$(".submit").click(function() {
Give your form a id like 'myform': <form method="POST" action="#" id="myform">
And use this for preventing default submission of form:
$("#myform").submit(function(e) {
e.preventDefault();
//your code
}
I am trying to add row with button click in table(Add Row). I am trying to add 2 fields dynamically.
1) slno
2) Date/ Time.
My problems :
1) Row is not getting added.
2) How to assign datepicker to "Date /Time" field, added dynamically.
Jsfiddle is http://jsfiddle.net/RXzs7/12/
Pl help.
html code :
<script>
$(document).ready(function() {
$('.date').each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0" });
});
});
</script>
<body>
<div id="lpage_container">
<div class="lform_container">
<h3>DETAILS OF LOCAL CONVEYANCE EXPENSES :</h3>
<form id="localexpenses" action="">
<table summary="local expense" id="localexpense_table" width="500" border="1">
<thead>
<tr>
<th width="1%" align="center"><strong>Sl.
No.</strong></th>
<th width="7%" align="center">
<strong>Date/Time</strong></th>
<th width="8%" align="center">
<strong>Remove</strong></th>
</tr>
</thead>
<tbody bgcolor="#CCCCCC">
<tr>
<td width="1%" align="center"><input type="text"
name="lsrno_00" id="srno_00" size="1" value="0"></td>
<td width="7%" align="center"><input type="text" class="date"
name="ldate_00" id="ldate_00" value="" size="8"></td>
<td> </td>
</tr>
</tbody>
</table>
<table summary="local buttons" width="500" border="1">
<tr>
<td align="right"><input type="button" value="Add Row"
id="add_ExpenseRowlocal">
</tr>
</table>
</form>
</div><!-- END subject_marks -->
<div class="clearfix"></div>
</div>
JS code :
$(function(){
// GET ID OF last row and increment it by one
var $lastChar =1, $newRow;
$get_lastID = function(){
var $id = $('#localexpense_table tr:last-child td:first-child input').attr("name");
$lastChar = parseInt($id.substr($id.length - 2), 10);
console.log('GET id: ' + $lastChar + ' | $id :'+$id);
$lastChar = $lastChar + 1;
$newRow = "<tr> \
<td><input type='text' name='lsrno_0"+$lastChar+"' value='0"+$lastChar+"' size='1'readonly /></td> \
<td><input type='text' class='date' name='ldate_0"+$lastChar+"' id='date_0"+$lastChar+"' size='8'/></td> \
<td><input type='button' value='Remove' class='del_ExpenseRowlocal' /></td> \
</tr>";
return $newRow;
};
// ***** -- START ADDING NEW ROWS
$('#add_ExpenseRowlocal').on("click", function(){
if($lastChar <= 9){
$get_lastID();
$('#localexpense_table tbody').append($newRow);
} else {
alert("Reached Maximum Rows!");
}
});
$(document).on("click", ".del_ExpenseRowlocal", function(){
$(this).closest('tr').remove();
$lastChar = $lastChar-2;
});
});
What jQuery version are you using? In your fiddle you have not added jQuery via the framework tab but under extenral resources you have two versions: 1.6.2 and 1.11.0. When I try and run it I get an error in the console that $().onis not a function. .on() came in jQuery 1.7 so if you are using 1.6.2 then you cannot use .on().
As for the date picker, when you run
$('.date').each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0"
});
in your document ready you add a date picker to all field with class date which currently exist. You must add the date picker to the new date fields after you have added the row to the DOM. Something like
$('.date', $('#localexpense_table tbody tr').filter(':last')).each(function() {
$(this).datepicker({ minDate:"-1m",maxDate:"0" });
});
after your .append() call should work.
Working fiddle (needs some styles fixing for the added rows)