I'm trying to achieve something similar to this :
I want to select a radio input and highlight a table row when someone clicks somewhere in the table .Same idea is this but with radio input
http://jsfiddle.net/FbHAV/2/
can I get some help ? What should I change in the Jquery?
HTML :
<table class="record_table">
<tr>
<td>
<input type="radio" />
</td>
<td>Hello</td>
<td>Hello</td>
</tr>
<tr>
<td>
<input type="radio" />
</td>
<td>Hello</td>
<td>Hello</td>
</tr>
<tr>
<td>
<input type="radio" />
</td>
<td>Hello</td>
<td>Hello</td>
</tr>
<tr>
<td>
<input type="radio" />
</td>
<td>Hello</td>
<td>Hello</td>
</tr>
Jquery :
$(document).ready(function () {
$('.record_table tr').click(function (event) {
if (event.target.type !== 'radio') {
$(':radio', this).trigger('click');
}
});
$("input[type='radio']").change(function (e) {
if ($(this).is(":checked")) {
$(this).closest('tr').addClass("highlight_row");
} else {
$(this).closest('tr').removeClass("highlight_row");
}
});
});
I think the major problem is that you forget to group the radio buttons, i.e
<input type="radio" name="test" />
Then this will work both when clicking on the radio button and the <tr> :
$(document).ready(function () {
$('.record_table tr').click(function (event) {
if (event.target.type !== 'radio') {
$(':radio', this).trigger('click');
}
});
$("input[type='radio']").change(function (e) {
e.stopPropagation();
$('.record_table tr').removeClass("highlight_row");
if ($(this).is(":checked")) {
$(this).closest('tr').addClass("highlight_row");
}
});
});
forked fiddle -> http://jsfiddle.net/48o1kycu/
Related
good evening, I have dynamically filled my table from the database. at the end of each row I have a button.
my idea is : when i clicked the button the row is hidden. I succes to recuperate the id of each row but jquery code does not work and my console doesn't return any error. i don't know where the problem is? or even if the process is correct.
also,at the latest i hope to replace the button with a checkbox but i don't know how to apply my idea with a checkbox
<table name="table" class="table" border="1">
<tbody>
<?php
include 'controller.php';
$controller1 = new Controller();
$res = $controller1->array();
while ($donne = $res->fetch()) {
?>
<tr id="<?php $donne['id'] ?>">
<td> <?php echo $donne['operateur'] ?></td>
<td> <?php echo $donne['machine'] ?></td>
<td> <?php echo $donne['declaration'] ?></td>
<td>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post' style="display: inline;">
<input type='hidden' id='id' name='id' value="<?php echo $donne['id']; ?>" />
<input type='submit' name='validate' id='validate' value='validate' />
</form>
</td>
</tr>
<?php
}
?>
</table>
and this is my jQuery code
if (isset($_POST['id']) && !empty($_POST['id'])) {
?>
<script>
$(document).ready(function () {
$("#validate").click(function () {
var i = $("#id").val();
var i = i.toString()
$("#" + i).hide();
});
});
</script>
<?php
}
use JQuery to hide the preferred row bi either id or class after loading dynamically.
this is an example:
// Denotes total number of rows.
var rowIdx = 0;
// jQuery button click event to add a row.
$('#addBtn').on('click', function () {
// Adding a row inside the tbody.
$('#tbody').append(`<tr id="R${++rowIdx}">
<td class="row-index text-center">
<p>Row ${rowIdx}</p></td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button">Remove</button>
</td>
</tr>`);
});
Consider the following.
$(function() {
$(".validate").click(function() {
var i = $(this).closest("tr").attr("id");
$("#" + i).hide();
var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
$.post(url, {
id: i,
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table name="table" class="table" border="1">
<tbody>
<tr id="row-1">
<td>
operateur 1
</td>
<td>
machine 1
</td>
<td>
declaration 1
</td>
<td>
<button class="validate">Validate</button>
</td>
</tr>
<tr id="row-2">
<td>
operateur 2
</td>
<td>
machine 2
</td>
<td>
declaration 2
</td>
<td>
<button class="validate">Validate</button>
</td>
</tr>
<tr id="row-3">
<td>
operateur 3
</td>
<td>
machine 3
</td>
<td>
declaration 3
</td>
<td>
<button class="validate">Validate</button>
</td>
</tr>
</table>
This will apply the callback to each Button. When the button is clicked,the Row is hidden and the ID is posted to your PHP Script.
i find my mistake .i have set the same id for each button,that's wrong,so i use class instead of id also in this way i could recuperate the id simply and apply .hide()
<script type="text/javascript">
$(".validate").click(function () {
var num = $(this).parents("tr").find("td:eq(0)").text();
alert(num);
});
</script>
i delete the form also because there is no need anmore
I'm building a dynamically generated table where every row is a form with some inputs and selects and has its own submit.
Here is my code so far:
<script>
$(function () {
$('form').on('submit', function (e) {
var princ = $('#principal').val();
window.princ = princ;
e.preventDefault();
$.ajax({
url: 'post.php',
method: 'GET',
data: {"princ":princ},
success: function (response) {
alert("success");
} }); }); });
</script>
<table id="assets_table">
<thead style=" cursor: pointer;">
<tr style="text-align: left; color: #fff;">
<th>Lender </th>
<th>Principal </th>
<th>Int. % </th>
<th>Term (mo.) </th>
<th>Collateral </th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$competitions_id = $uscom['id'];
$users_query = mysqli_query($con, "SELECT * FROM competitions WHERE competition='$compe'");
$users_query_r = mysqli_fetch_array($users_query);
foreach($users_query as $users_query_r) {
$usn = $users_query_r['Name'];
$usn_query = mysqli_query($con, "SELECT * FROM users WHERE username='$usn'");
$usn_query_r = mysqli_fetch_array($usn_query);
?>
<form>
<tr>
<td> <img src="<?= $punch_query_r['profile_pic'] ?>" alt="user"> <?= $users_query_r['Name'] ?></td>
<td><input id="principal" type="text" value="0" ></td>
<td><input id="rate" type="text" value="0" ></td>
<td><input id="term" class = "term_input" type="text" value="0" ></td>
<td><input id="collateral" type="text" value="0">
<select id="colselect" >
<option selected disabled>Select asset</option>
</select></td>
<td> <input type="submit"></td>
</tr>
<?php
} ?>
</tbody>
</table>
</form>
However I cannot make it work properly because when I click on submit it does not really submit the corresponding row's form but the first one that was submitted.
I've also tried rewritting variables with input paste keyup but it does not solve the problem either because it just gets the last input whch was filled regardless of the row.
Any idea on how to solve it? Many thanks in advance.
I would like to sort a table with data row from MySQL then change the order and submit it.
I used jQueryUI.sortable to make those tr tag (row) draggable.
But when I submitting the form, some of them didn't changed order.
Why? I tried to figure it out, I var_dump the data I submitted and I found a problem:
The tr tag (row) I moved from the original order, won't pass to PHP so var_dump will not show the row ID.
To make it easier to understand, I post my code here:
HTML Code
<table>
<thead>
<tr>
<th>Subject</th>
<th>Content</th>
</tr>
</thead>
<tbody id="sortable">
<tr>
<td>
Hello World
<input name="displayorder[]" type="hidden" value="1" />
</td>
<td>I come from Mars!</td>
</tr>
<tr>
<td>
Hello Mars
<input name="displayorder[]" type="hidden" value="2" />
</td>
<td>I come from Jupiter!</td>
</tr>
<tr>
<td>
Hello StackOverflow
<input name="displayorder[]" type="hidden" value="3" />
</td>
<td>I come from North Korea ...</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="2"><input type="submit" value="Submit!" />
</tr>
</tbody>
</table>
I omitted the form content cause it is not important
JavaScript (Sortable Library loaded)
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.6,
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
$displayorder = $_POST["displayorder"];
if($displayorder != "") {
$order = 1;
foreach($displayorder as $value) {
mysql_query("UPDATE message SET displayorder=$order WHERE announcementid=$value");
$order++;
}
}
I will prefer not using Ajax to do this because I have dozens of similar page to do the same task.
Thanks in advance.
Well I decided to code it every page.
The code now:
JavaScript
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.4,
update: function(event, ui){
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/update.php?action=displayorder'
});
},
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
foreach($_POST["displayorder"] as $i => $value) {
mysql_query("UPDATE message SET displayorder=$i WHERE announcementid=$value");
$i++;
}
So I just got done with figuring out some javascript issues with my form in this topic: How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?
But since I had such a multi-part question I have been asked to create a new topic. Below is my new code that I am using where I am stuck and wanting to be able to submit my form, which has the capability if adding multiple rows, to my database and add those HTML rows to rows in the SQL database, respectively.
PREVIEW: http://cl.ly/image/0K0Z202O1Q3e/Screen%20Shot%202013-03-14%20at%203.00.19%20PM.png
HTML
<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>
<input type="hidden" id="co_city" name="co_city">
<input type="hidden" id="co_state" name="co_state">
<input type="hidden" id="co_zipcode" name="co_zipcode">
<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
<td><select id="company_name" name="company_name" /></select></td>
<td><input name="co_name" type="text"></td>
<td><input type="submit" value="Get GPS" onclick="gpslookup();" /></td>
<td><input id="co_lat" name="co_lat" type="text" /></td>
<td><input id="co_long" name="co_long" type="text" /></td>
<td><input id="co_address" name="co_address" type="text" /></td>
</tr>
</table>
<table id="tabledata">
<thead>
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input type="checkbox" /></td>
<td><input name="border_location" type="text" /></td>
<td><input name="cable_location" type="text" /></td>
<td><input name="vault_direction" type="text" /></td>
<td><input name="cable_type" type="text" /></td>
<td><input name="cable_size" type="text" /></td>
<td><input name="cable_gauge" type="text" /></td>
<td><input name="vertical" type="text" /></td>
<td><input name="jumpers" type="text" /></td>
<td><input name="protectors" type="text" /></td>
<td><input name="metered_dist" type="text" /></td>
<td><input name="comments" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button onclick="deleteRow(); return false;">Delete Row</button>
<button id="ActionSubmit">Submit</button>
</body>
</html>
scripts.js
//Button Functions
$(function () {
var addInputRow = function () {
$('#input').append($('#template').html());
};
addInputRow();
$('#ActionAddRow').on('click', addInputRow);
$('#ActionSubmit').on('click', function () {
var data = $('#input tr').map(function () {
var values = {};
$('input', $(this)).each(function () {
values[this.name] = this.value;
});
return values;
}).get();
$.post('./php/upload_survey.php', {
json: JSON.stringify(data),
delay: 1
}).done(function (response) {
alert("Thank you. Your form has been submitted.");
console.log(response);
});
});
});
//Delete Selected Rows
function deleteRow() {
try {
var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 3) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
catch(e) {
alert(e);
}
};
upload_survey.php
//Assign passed parameters
$values = json_decode($_POST['json']);
$stringLogInfo = "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
log_audit($logAuditFile, $logModule, $stringLogInfo);
//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Insert Survey Form Information into the database
$sql="INSERT INTO table_name (company_name,...,...)
VALUES ($values)";
mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());
**So far every time I try to get this working the JS fires successfully, but I get an error in Chrome's Developer Toolbox: Unable to Make Query:Column count doesn't match value count at row 1
This refers to this function in js file: console.log(response);
I think there is no such thing as batch inserts in PHP. There is no equivalent for JAVA's addBatch & executeBatch.
So the right way to do it is simply iteratation over array and insert single row with prepared statement.
How to Save value of check-box within 5 columns to database (PHP and JQUERY) ?
PHP code are dispay 6 columns. there 5 columns contain check-box that loop from database.
---PHP-----------------------------------
<table id="tblISP" border="0">
<tr>
<th style="width:20px">
</th>
<th>
MenuID
</th>
<th>
Menu
</th>
<th>
Delete
</th>
<th>
Upddate
</th>
<th>
View
</th>
<th>
Save
</th>
</tr>
<tr>
<td>ALL <input type="checkbox" class="menuiddd" name="checkmenuid" id="checkmenuid"/></td>
<td> </td>
<td> </td>
<td>ALL<input type="checkbox" class="menuidddel" name="checkdelete" id="checkdelete"/></td>
<td>ALL<input type="checkbox" class="menuiddupdate" name="checkupdate" id="checkupdate"/></td>
<td>ALL<input type="checkbox" class="menuiddview" name="checkview" id="checkview"/></td>
<td>ALL<input type="checkbox" class="menuiddsave" name="checksave" id="checksave"/></td>
</tr>
<tr>
<td>
<input type="checkbox" class="menuiddd" name="idd[]" id="idd[]" value="<?php echo $row["mid"]; ?>"/>
</td>
<td>
<?php echo $row["mid"]; ?>
</td>
<td>
<?php echo $row["mname"]; ?>
</td>
<td>
<input type="checkbox" class="menuidddel" name="del[]" id="del[]" value="chkdel" />
</td>
<td>
<input type="checkbox" class="menuiddupdate" name="upd[]" id="upd[]" value="chkupd" />
</td>
<td>
<input type="checkbox" class="menuiddview" name="vie[]" id="vie[]" value="chkvie" />
</td>
<td>
<input type="checkbox" class="menuiddsave" name="sav[]" id="sav[]" value="chksav" />
</td>
</tr>
<tr>
<td colspan="3">
<!--<a id="hlsa" href="javascript:exit(0);">Select All</a>
<a id="hldsa" href="javascript:exit(0);">DeSelect All</a>-->
</td>
</tr>
<tr>
<td colspan="3" align="center">
<hr/>
<input type="button" value="Save" id="btSave" name="btSave" style="cursor:pointer;float:none" class="allbutton">
</td>
</tr>
<tr>
<td colspan="3" id="dvProc1" align="center">
</td>
</tr>
</table>Save check-box value within 5 columns to database
------------------Jquery------------
Jquery reaction when click button save then get information from check box save to database.
$(document).ready(function (){
$("#btSave").unbind();
$("#btSave").click(function(){
var idd = [];
var del = [];
var upd = [];
var vie = [];
var sav = [];
$("input[name='idd[]']:checked").each(function() {
idd.push($(this).val());
});
$("input[name='del[]']:checked").each(function() {
del.push($(this).val());
});
$("input[name='upd[]']:checked").each(function() {
upd.push($(this).val());
});
$("input[name='vie[]']:checked").each(function() {
vie.push($(this).val());
});
$("input[name='sav[]']:checked").each(function() {
sav.push($(this).val());
});
var mainarray=[idd,del,upd,vie,sav];
var transposed = mainarray.transpose();
//-----------------------alert(str);--note--need return-------------
alert(transposed.join(';'));
})
$("#checkmenuid").click(function(){
$('.menuiddd').attr('checked', $( this ).is( ':checked' ) ? 'checked' : "");
});
$("#checkdelete").click(function(){
$('.menuidddel').attr('checked', $( this ).is( ':checked' ) ? 'checked' : "");
});
$("#checkupdate").click(function(){
$('.menuiddupdate').attr('checked', $( this ).is( ':checked' ) ? 'checked' : "");
});
$("#checkview").click(function(){
$('.menuiddview').attr('checked', $( this ).is( ':checked' ) ? 'checked' : "");
});
$("#checksave").click(function(){
$('.menuiddsave').attr('checked', $( this ).is( ':checked' ) ? 'checked' : "");
});
});
</script>
I'm not entirely sure I've identified your question, but before you deal with any jQuery you should build a functioning system without any javascript. Rather than defining a non-standard method for dealing with the form's submission, you can simply write it normally before adding a clean layer of javascript to handle asynchronous submission.
Firstly, you need to wrap your input elements in a form element, and then write a PHP script to analyse the global $_POST array and to execute the various database commands as required. You can use this PHP layer for the logic of identifying what calls should be made to the database, based on what the user has selected on the form. Note that checkboxes that are unchecked are not actually sent in the POST request, so you'll have to use isset() in PHP to know if they were unchecked.
Once that's arranged, you can use jQuery to submit the form asynchronously, and you won't cause a page refresh:
$(function() {
$('form#yourformid').submit(function(event) {
event.preventDefault(); // stop the page from redirecting
// serialise your form's data, and send it in a POST request
// to the form's action attribute
$.post(
$(this).attr('action'),
$(this).serialize(),
function() {
alert('Data successfully saved.');
});
});
});