I have a checkbox where the values are dynamically populated from the data on my database. I would like to perform further queries based on the clicked checkbox, however I cant seem to retrieve the ID whenever I click on any of the checkboxes. I do not want to use a submit button. How can this be achieved??
My code.
function getDBlist() {
global $link;
$qry = ("SHOW DATABASES");
$res = mysqli_query ( $link, $qry );
while ( $row = mysqli_fetch_assoc ( $res ) ) {
echo '<input type="checkbox" name="db" id="' . $row ['Database'] . '" value="' . $row ['Database'] . '" />';
echo $row ['Database'];
}
}
getDBlist ();
My Script
$(document).on("change","checkbox", function() {
var val = $(this).val();
var id = this.id;
alert(val, id);
});
When I click on any of the checkboxes I don't get an alert with either the value or the ID. What am I doing wrong here? Could it be because of my dynamically generated ID?
To bind change event to the dynamically generated checkboxes you need to delegate change event like below
$(document).on("change",".checkbox", function() {
var val = $(this).val();
var id = this.id;
alert(val, id);
});
Above code will work for both existing and dynamically created checkboxes. Here document object will delgate change event to checkboxes with class="checkbox"
Also as mentioned by #Ghost, you need to add class to dynamically generated checkboxes like below
echo '<input type="checkbox"
name="db" id="' . $row ['Database'] . '"
value="' . $row ['Database'] . '"
class="checkbox"/>';
More Information for .on()
Looking at your echo statement rendering the markup, you haven't designated class="checkbox" at all:
echo '<input type="checkbox" name="db" id="' . $row ['Database'] . '" value="' . $row ['Database'] . '" />';
Since you haven't added it, pointing to $(".checkbox") won't work. You need to add them in the echo.
Your jquery selector is looking for an element with the css class `checkbox', either add this class to your html:
echo '<input type="checkbox" class="checkbox"...';
Or remove the period in the selector, to target all checkbox elements:
$("checkbox").on("change", function() {
var val = $(this).val();
var id = this.id;
alert(val, id);
});
Try this
$("body").on("change",".checkbox", function() {
var val = $(this).val();
var id = $(this).attr("id");
alert(val, id);
});
Related
I want rest the value in the text box when the rest button click in dynamical created table .how do i do it?
$table .='<tbody><tr>';
$table .='<td>' . $row["emp_id"] . '</td>';
$table .='<td>' . $row["emp_name"] . '</td>';
$table .='<td>' . $row["date"] . '</td>';
$table .='<td><input type="text" name="firstname" class="form-control" value="'.$row["ot_hour"] .'" size="4"></td>';
$table .='<td><button type="button" name="ot_approval_rset" class="btn btn-primary btn-sm ot_approval_rset" " id="'.$row["emp_id"].'">Reset</button></td>';
$currentMonth= date('Y-m');
$query01 ="SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `ot_hour` ) ) ) AS timeSum
FROM otresquest
WHERE emp_id ='".$row["emp_id"]."' AND date LIKE '$currentMonth%' AND overtime_status=6";
$statement = $connect->prepare($query01);
if($statement->execute())
{
$result = $statement->fetchAll();
foreach($result as $row){
$table .='<td>' . $row["timeSum"] . '</td>';
}
}
$table .='</tr></tbody>';
java script code
$(document).on('click', '.ot_approval_rset', function() {
emp_id = $(this).attr('id');
//i need write code here to reset (00:00:00) value of ot_approval_rset input box
});
when click the reset button particular row ot hours should 00:00:00 .
Let try this code
$(document).on('click', '.ot_approval_rset', function() {
var otherInput = $(this).closest('tr').find('input').val('00:00:00');
});
It may be help to you
In my DB i have created a table named "coursePlaces" in which i have 7 columns and a number of rows.
Loading the php-file course.php I connects to the db and selects data from the table "coursePlaces" using it to echo a number of buttons with different id and value each:
<?php
/* CONNECTION TO DB */
require 'includes/dbh.inc.php';
/* ACCESS COURSE AND GRADE VAR FROM URL WITH GET */
$course = $_GET['course'];
$grade = $_GET['grade'];
/* SELECTS DATA FROM TABLE AND ECHOES BUTTONS WITH DIFFERENT ID AND VALUE DEPENDING ON TABLE CONTENT */
$sql = "SELECT * FROM coursePlaces WHERE grade='$grade' AND course='$course'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '">';
}
/* CONVERTS VAR TO USE IN JQUERY SCRIPT */
echo '<script>';
echo 'var grade = ' . json_encode($grade) . ';';
echo 'var course = ' . json_encode($course) . ';';
echo '</script>';
?>
<script src="includes/global.inc.js"></script>
<!-- DIV TO ECHO OUTPUT FROM PLACE.INC.PHP -->
<div class="selectedPlace" id="selectedPlace"></div>
When clicking one of the buttons the value should be send to the file "global.inc.js" In which i have placed a script used to listen for clicks:
$('input#$row['placeName']').on('click', function() {
var place = $('input#place-$row['placeName']').val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
My problem is, that I don't know what the name of the button id is - since it is created from a varchar in a database table. How do i bring this information over into my .js file, so the script posts individual value from button no matter what button the user presses on the courses.php.
Use jQuery to set your variable with Ajax ( method POST ).
Try to change code as below:
$('input[type="submit"]').on('click', function() {
var place = $(this).val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
set on click attribute when you echo your inputs:
echo sprintf('<input type="submit" id="place-%s" value="%s" onclick="yourfunction("%s", "%s", "%s") >', $row['placeName'], $row['placeName'], $grade, $course);
and separate this yourfunction function:
function yourfunction(place, grade, course){
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
You should use a generic click handler instead of the one you are using.
If all button have one common class you can listen to the click of all.
Add class inputBtn to following:
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '" class="inputBtn">';
Change
$('input#$row['placeName']').on('click', function() {
to
$('.inputBtn').on('click', function() {
var btnID = $(this).prop('id');
var spltID = btnID.split('-'); //split from the - & spltID[1] will contain the part that you required.
}
This code is written like just for the sake of clarity. It is possible to make it more optimal like split() function can be called on btnID to reduce code line.
I tried looking for a solution everywhere for my question and I can't seem to find it so I decided to ask it myself. Well, I'm working on a project where I'm creating multiple input fields with JavaScript, here is the code:
HTML:
<form id="buildyourform">
<legend>Registration Page</legend>
<hr>
<input type="button" value="New Registry" class="add" id="add" />
<input type="submit" value="Save" id="submitForms" />
<hr>
<script>myscript</script>
</form>
The JavaScript code inside the <script> tags above:
<script>
$(document).ready(function() {
$("#add").click(function() {
var lastField = $("#buildyourform div:last");
var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
fieldWrapper.data("idx", intId);
var fName = $("<input type=\"text\" class=\"fieldname\" placeholder=\"Name of New Registry\" name=\"field\" />");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"x\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
</script>
The thing is that this works, it allows me to create and remove dynamically input fields, the problem is that they are all generated with the same name, so my question is: how do I add every single of them and their value in my database? This is my current php code:
<?php
require_once 'conector_superadmin.php';
$link = connect($conn);
$NameRegistryInput = $_POST['field'];
$sql = "INSERT INTO `database` (`idRegistryName`, `Name`) VALUES (NULL, '$NameRegistryInput');";
mysqli_query($link, $sql);
?>
If these were static fields I wouldn't have a problem, but the fact that they're dynamic got me stuck, so any help would be greatly appreciated.
EDIT
My new PHP code looks like this now (I also added the "[]" to the name in the input field, it now looks like this "field[]"):
require_once 'conector_superadmin.php';
$link = connect($conn);
foreach ($_POST['field'] as $NameRegistryInput) {
$sql = "INSERT INTO `database` (`idRegistryName`, `Name`) VALUES (NULL, '$NameRegistryInput');";
mysqli_query($link, $sql);
}
It still doesn't work.
PHP handles a form post containing multiple elements with the same name as an array - as long as you add [] to the name attribute
So,
var fName = $("<input type=\"text\" class=\"fieldname\" placeholder=\"Name of New Registry\" name=\"field[]\" />");
then
foreach ($_POST['field'] as $NameRegistryInput) {
$sql = "INSERT INTO `database` (`idRegistryName`, `Name`) VALUES (NULL, '$NameRegistryInput');";
mysqli_query($link, $sql);
}
Now, I see you inventing ids in javascript for each element you are adding to the page. I think you will find that you don't need that at all.
I am have this issue:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do.
The second select list is empty initially.
I want to fill it with values depending of what is chose in first select list.
How can I do that? To fill the second select list only if something is selected in first select list.
MrCode has a nice example for you.
Using Ajax To Populate A Select Box
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with
The best way to handle this would be to populate the list after you made a change on the first list. For example.
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. for example your some.php will take a value parameter. The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}]. Please keep this in mind.
I have set of dynamically generated checkboxes. I want to select them by change event. Means get the changed checkbox id.
My PHP/HTML:
$sql = "SELECT * FROM tbl_category order by categoryodr asc";
$result = mysql_query($sql) or die(mysql_errno());
while ($valuesca = mysql_fetch_array($result)) {
echo'<input class="checkbox" type="checkbox" name="category[]" id=' . $valuesca['catid'] . ' onclick="wedCheck(' . $valuesca['catid'] . ')" value="' . $valuesca['catid'] . '"/> ';
}
My jquery:
$('.checkbox').on("#id").change(function() {
var txtval = $(":checkbox").on("#id").val();
});
I always get the 1st id on jquery but the html ids are correct.
The syntax for your .on call is incorrect:
$(".checkbox").on("change", function() {
var val = $(this).val();
var id = this.id;
});