I have a MySQL database table which has a unique ID identifier for each line:
id text cat
4 abc 1
233 bbb 2
45 efa 1
Using PHP, I show an HTML table where you can see the TEXT and CAT fields.
Each row of the table is shown using a "while" loop.
As you can see, I also store the IDs in the array $val.
<?php
....
$val = array();
while($objResult = mysql_fetch_array($objQuery)){
$val[] = $objResult["id"];
?>
<table>
<tr>
<td><?php echo $objResult["text"];?></td>
<td><?php echo ''.$objResult["cat"].'';</td>
<tr>
<?php
}
?>
</table>
Now comes the tricky part.
Using JQuery, I would like to be able to click on the CAT cells in the html table and open a dialog window where I can change the value of CAT.
Here is the form:
<form action="modcat.php" method="POST" id="modcat">
<table>
<tr>
<td>
<select id="cat">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<input type="hidden" name="val" value="<?php
for ($i = 0; $i < 1000; $i++) {
echo $val[$i];
}
?>">
</td>
</tr>
</table>
</form>
<script>
$(document).ready(function () {
$("a#open").click(function () {
$('#finestra').dialog("open");
return false;
});
$('#finestra').dialog({
modal: true,
autoOpen: false,
buttons: [{
text: "modifica",
click: function () {
submitform();
$(this).dialog("close");
}
}, {
text: "annulla",
click: function () {
$(this).dialog("close");
}
}]
});
function submitform() {
$('#modcat').submit();
}
});
</script>
As you can see, I am trying to send to the form the corresponding value of ID (through a hidden input).
As it turns out, I put together all the IDs of all the table in the array $val.
How can I send to the form just the one which is chosen?
You can add the id to the html someplace, retrieve it in the click function, and add it to the form before submitting.
Here, i am adding the id as a data attribute, i also changed the id on the a element to a class, since your rendered html will contain multiple a elements, and ids should be unique
while($objResult = mysql_fetch_array($objQuery)):?>
<table>
<tr>
<td><?= $objResult['text'];?></td>
<td>
<a href="#" class="open" data-id="<?=$objResult['id'];?>">
<?=$objResult['cat'];?>
</a>
</td>
<tr>
</table>
<?php endwhile;
For the form, dont prepopulate the hidden field, just give it an id so its easy to target in js:
<form action="modcat.php" method="POST" id="modcat">
<table>
<tr>
<td>
<select id="cat">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<input type="hidden" name="val" id="hidden-id">
</td>
</tr>
</table>
</form>
Then in your js update the value from the data attribute:
$(document).ready(function () {
$("a.open").click(function () {
var clickedLink = $(this); //get clicked link
var id = clickedLink.data('id'); //extract id from data attribute
$('#hidden-id').val(id); //update hidden field value with id
$('#finestra').dialog("open");
return false;
});
...
Related
I have a table with a select box that I want to be disabled by default (for safety purposes). Now, when the edit button from jquery-tabledit is clicked, I want it to be enabled again. How could I achieve so? When clicking on Save, action_user_2.php gets called with [action] => edit, but I need to listen when edit button gets click on the same page so that I can change the select box to "select name='selectbox'" (removing disabled).
<!--User Approval-->
<td>
<form method='POST'>
if ($row_approved['admin_approved'] == 'Approved') {
echo "<select disabled name='selectbox' onchange='this.form.submit()'>
<option value='Approved' selected>Approved</option>
<option value='Disapproved'>Disapproved</option>
</select>";
} else if ($row_approved['admin_approved'] == 'Disapproved') {
echo "<select name='selectbox' onchange='this.form.submit()'>
<option value='Approved'>Approved</option>
<option value='Disapproved' selected>Disapproved</option>
</select>";
}
echo "
</form>
</td>
<!--User Roles-->
<td>
<form method='POST'>
<select disabled class='roles_checkbox' multiple='multiple' name="roles_checkbox[]"
onchange='this.form.submit()'>
</select>
<?php
echo "
</form>
</td>
<script>
$(document).ready(function () {
$('#editable_table').Tabledit({
// when click on save; action_user_2.php gets called
url: 'action_user_2.php', // where data will be sent
data: {approved_status: approved_status},
columns: {
identifier: [0, "user_id"],
editable: [[1, 'first_name'],
[2, 'last_name'],
[3, 'email']]
},
// hide the column that has the identifier
hideIdentifier: true,
// activate focus on first input of a row when click in save button
autoFocus: true,
// activate save button when click on edit button
saveButton: true,
restoreButton: false,
onSuccess: function (data, textStatus, jqXHR) {
var htmlString = "<?php echo 'User information has been updated'; ?>";
alert(htmlString);
// custom action buttons
if (data.action === 'delete') {
$('#' + data.id).remove();
}
}
});
});
$('#editable_table').DataTable();
</script>
action_user_2.php
$input = filter_input_array(INPUT_POST);
print_r($input);
console->network->action_user_2.php
Array ( [user_id] => 4 [first_name] => New [last_name] => User [email] => tes#gmail.com [action] => edit )
if I understand correctly you want to click the edit button to edit the current row fields, and the select with name="roles_checkbox[]" to become name="selectbox" and also remove disabled attribute?
if yes then you can try the "onclick" event I've added
......
.......
$(document).ready(function () {
$(document).on("click", ".tableit-edit-button", function() {
$(".roles_checkbox").attr("name", "selectbox").removeAttr('disabled');
});
$('#editable_table').Tabledit({
.........
.........
You can use $(this).closest("tr").find("[name=selectbox]") here closest() will get tr where button is been clicked and then find() method will find your select-box inside that tr then simply remove disabled from that select-box
Demo Code :
$('#editable_table').Tabledit({
//some codes...
columns: {
identifier: [0, "user_id"],
editable: [
[1, 'first_name'],
[2, 'last_name'],
[3, 'email'],
]
},
// hide the column that has the identifier
hideIdentifier: true,
// activate focus on first input of a row when click in save button
autoFocus: true,
// activate save button when click on edit button
saveButton: true,
restoreButton: false,
onSuccess: function(data, textStatus, jqXHR) {
var htmlString = "<?php echo 'User information has been updated'; ?>";
alert(htmlString);
// custom action buttons
if (data.action === 'delete') {
$('#' + data.id).remove();
}
}
});
$(document).on("click", ".tabledit-edit-button", function() {
//get closest tr and then find slectbox and disable same
$(this).closest("tr").find("[name=selectbox]").removeAttr('disabled')
$(this).closest("tr").find("[name*=roles_checkbox]").removeAttr('disabled')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-tabledit#1.0.0/jquery.tabledit.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<table class="table table-bordered" id="editable_table">
<thead class="thead-dark">
<tr>
<th>user_id</th>
<th>first_name</th>
<th>last_name</th>
<th>email</th>
<th>Approved</th>
<th>Soemthing</th>
<th class="tabledit-toolbar-column"></th>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td>
Soemthing..
</td>
<td>
Soemthing..1
</td>
<td>
Soemthinga#gmail.com
</td>
<td>
<form method='POST'>
<select disabled name='selectbox' onchange='this.form.submit()'>
<option value='Approved' selected>Approved</option>
<option value='Disapproved'>Disapproved</option>
</select>
</form>
</td>
<!--User Roles-->
<td>
<form method='POST'>
<select disabled class='roles_checkbox' multiple='multiple' name="roles_checkbox[]" onchange='this.form.submit()'>
<option value='1' selected>1</option>
<option value='2'>2</option>
</select>
</form>
</td>
</tr>
<tr>
<td>
2
</td>
<td>
Soemthing..
</td>
<td>
Soemthing..2
</td>
<td>
Soemthinga#gmail.com
</td>
<td>
<form method='POST'>
<select disabled name='selectbox' onchange='this.form.submit()'>
<option value='Approved' selected>Approved</option>
<option value='Disapproved'>Disapproved</option>
</select>
</form>
</td>
<!--User Roles-->
<td>
<form method='POST'>
<select disabled class='roles_checkbox' multiple='multiple' name="roles_checkbox[]" onchange='this.form.submit()'>
<option value='1' selected>1</option>
<option value='2'>2</option>
</select>
</form>
</td>
</tr>
</tbody>
</table>
Only the first row is updating.. I was able to create a dynamically created select tags and button but every time I were to choose to the drop down, only the first row is being updated and the other rows will alert only "choose first" even though i already selected an option.
jquery func'
$('input').each(function(){
if($(this).attr("type")=="button"){
$(this).click(function{
var empid=$('#emp').val();
var job=$('#jobselect').val();
if(job !== "NULL"){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>userskills/update",
data:{'Emp_ID':empid,'Job':job},
cache: false;
success:
function(data){
alert("Updated!");
}
});
}else{
alert("Choose first");
}
});
}
});
this is my tbody in the table
<tbody>
<?php foreach($job as $temp): ?>
<tr>
<td><?php echo $temp->Name?></td>
<td><?php echo $temp->Group?></td>
<td><?php echo $temp->Section?></td>
<td>
<select id="jobselect">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role->RoleID">"><?php echo $role->RoleName?></option>
<?php endforeach; ?>
</select>
<input type="hidden" id="emp" value="<?php echo $temp->JobID?>" />
<input type="button" id="update"/>
</td>
</tr>
<?php endforeach; ?>
</tbody>
The id attribute is supposed to be unique within the document, so your current code creates invalid HTML. The browser won't be too bothered by it and will display your elements anyway, but then in JS if you select by element ID (like '#jobselect') you only get back the first element with that ID.
You should switch to use a common class instead, and then in your JS use DOM navigation to get from the clicked button (referenced by this) to its related controls using .closest() to get the containing td element and then .find() to get the items within that td:
$('input[type="button"]').click(function(){ // no need for .each()
var container = $(this).closest('td'); // 1. get common parent element
var empid = container.find('.emp').val(); // 2. note the use of .find() with
var job = container.find('.jobselect').val(); // class selectors here
if (job !== "NULL") {
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>userskills/update",
cache: false;
success:
function(data){
alert("Updated!");
}
});
} else {
alert("Choose first");
}
});
<tbody>
<?php foreach($job as $temp): ?>
<tr>
<td><?php echo $temp->Name?></td>
<td><?php echo $temp->Group?></td>
<td><?php echo $temp->Section?></td>
<td>
<select class="jobselect">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role->RoleID">"><?php echo $role->RoleName?></option>
<?php endforeach; ?>
</select>
<input type="hidden" class="emp" value="<?php echo $temp->JobID?>"
<input type="button" class="update"/>
</td>
</tr>
<?php endforeach; ?>
</tbody>
Note that you don't need the .each() loop at all if you change your selector to just get the input elements that are buttons.
hi i'm using select2 to style my dependent dynamic dropdown list on my php file, the problem is when i select a value from 1st dropdown to fetch data from mysql DB to 2nd dropdown list it goes to it's default style so i need some solution to solve the problem here is my files.
select2 script:
<script type="text/javascript">
$(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>
index.php:`
<form name="form1" action="test.php" method="post">
<table>
<tr>
<td>
<select name="brand" id="branddd" class="js-example-basic-single" required>
<option disabled selected required >brand</option>
<?php
$res=mysqli_query($link,"select * from brand");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<select name="model" id="model" class="js-example-basic-single" required>
<option disabled selected required >model</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
script to fetch DB values:
<script type="text/javascript">
function change_brand()
{
var xmlhttp=new XMLHttpRequest () ;
xmlhttp.open("GET","ajax.php?brand="+document.getElementById("branddd").value,false) ;
xmlhttp.send(null) ;
document.getElementById("model").innerHTML=xmlhttp.responseText ;
}
$(function(){
$('#branddd').on('change',function(){
this.value && // if value!="" then call ajax
$.get('ajax.php',{brand:this.value},function(response){
$('select[name="model"]').html(response);
});
});
});
</script>
ajax.php:
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"test_db");
$brand=$_GET["brand"];
if($brand!="")
{
$res=mysqli_query($link,"select * from model where brand_id=$brand");
echo "<select>";
while($row=mysqli_fetch_array($res))
{
echo "<option>"; echo $row["name"]; echo "</option>";
}
echo "</select>";
}
?>
This is your styled select element:
<select name="model" id="model" class="js-example-basic-single" required>
You need to add the name, id, and class attributes to your PHP echo. Something like this:
echo "<select name=\"model\" id=\"model\" class=\"js-example-basic-single\" required>";
But a much better way would be to not write out a new select element and replace it with the html function. Instead, output the data from your PHP page as a JSON object, then add those options to the select element.
JSON object:
{
"option1": "Data A",
"option2": "Data B",
"option3": "Data C"
}
JavaScript:
function change_brand() {
$.ajax({
url: "ajax.php?brand="+document.getElementById("branddd").value,
dataType: "json",
success: function(data) {
var name, select, option;
select = document.getElementById('model');
// Clear the old options
select.options.length = 0;
// Load the new options
for (name in data) {
if (data.hasOwnProperty(name)) {
select.options.add(new Option(data[name], name));
}
}
}
});
}
I am new in php.I made and html Dynamic Table on which there are 2 following fields that are dynamically generated
for each time the user presses Add/Remove Button:
Image Sample given below:
Here the html Code given below:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border-collapse: collapse;
}
</style>
<script>
function addMore() {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var x = document.getElementById("myTable").rows[1].cells;
cell1.innerHTML = x[0].innerHTML;
cell2.innerHTML = x[1].innerHTML;
}
function removeLast() {
document.getElementById("myTable").deleteRow(-1);
}
</script>
</head>
<body>
<form action="data.php" method="post">
<table id="myTable">
<tr>
<th>Options</th>
<th>User Input</th>
</tr>
<tr>
<td>
<select class="mySelect" name="DESCR" >
<option disabled="" selected="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
</td>
<td> <input type="text" name="ALAMT"></td>
</tr>
</table>
</form>
<br>
<button onclick="addMore()">Add New</button>
<button onclick="removeLast()">Remove</button>
<button onclick="myFunction()">Try it</button>
</body>
</html>
After choosing option and inputing vaules to this table,i want to submit their data to php using $_POST[ ]
Because they are Dynamic,it will be time consuming & inefficient to maintain unique name or Id for each of
them.So,What code should i write in php to do so.please let me know for any further information.Thanks
You Have to Take array as name of the new added field everytime. and that find the array count and make loop and get the value and put that value in the insert query.
used this script to add whole the textboxes
<script type="text/javascript">
$(document).ready(function () {
$('.add_more').live('click', function () {
$(this).before('<div class="one del"> <div class="two"><label class="label" for="name">Title:</label><input type="text" class="validate[required]" value="" name="caption[]" /></div><div class="two"><label class="label" for="name">Value:</label><input type="text" class="validate[required]" value="" name="values[]"/></div><i class="fa fa-trash-o add_del"></i></div>');
});
$('.add_del').live('click', function () {
$(this).parent().remove()
});
});
</script>
Then
for ($i = 0; $i < count($_POST['caption']); $i++) {
$caption = $_POST['caption'][$i];
$sp_values = $_POST['values'][$i];
$sql1 = "INSERT INTO `sub_project` (`parent`, `sp_title`, `sp_values`) VALUES ('$insert', '$caption', '$sp_values')";
$insert1 = $obj_db->sqlquery($sql1);
}
Hope this help you
I am trying to retrieve on server-side the value from the selected option sent using a jQuery .load() call like this:
<script type="text/javascript">
$(function () {
$("#first").change(function () {
$("#second").load('populate_section.php?year=', {first: $(this).val()});
});
});
</script>
<tr>
<td>
<select id="first" name="year">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</td>
</tr>
<tr>
<td>
<select id="second" name="section">
</select>
</td>
</tr>
Then how I try to retrieve the value in my PHP code :
<?php
$year = $_GET['year']; // for test only
echo "<option>" . $year . "</option>";
?>
I assume here that the result will be a dropdown box with a value of whatever I chose on the first dropdown. However, it seems that var $year is empty.
Thanks.
You have not set any value for "year" GET variable in the URL.
If you need to send $(this).val() as the "year", do it like below code.
$("#second").load('populate_section.php', {"year": $(this).val()});
Try this:
$(function () {
$("#first").change(function () {
$("#second").load('populate_section.php', {year: $(this).val()});
});
});