Select dynamic checkbox id using jquery - javascript

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;
});

Related

How do I fetch values from database and display them in select option in javascript

I have created below code to do calculation on the data fetched from database. Steps:
Fetch the value that will be used by javascript to do calculation from database and display using 'u" value="'
Do calculation using javascript using the values fetched. 'u'
All what i require is to fetch those values and use it to calculate in JavaScript but nothing happens.
Below code fetches the data and values
<select name="urgency" id="urgency" class="form-control" onchange="caltotal()">
<?php
$query = $conn->query("SELECT idurgency,amount_added,value,hours_day FROM cww_avid_urgency");
foreach ($query as $key => $row) {
if ($row['idurgency'] == $post['urgency']) {
echo '<option selected="selected" id="' . $row['idurgency'] . 'u" value="' . $row['idurgency'] . '" title="' . $row['amount_added'] . '">' . $row['value'] . $row['hours_day'] . '</option>';
}
else {
echo '<option selected="selected" id="' . $row['idurgency'] . 'u" value="' . $row['idurgency'] . '" title="' . $row['amount_added'] . '">' . $row['value'] . $row['hours_day'] . '</option>';
}
}
?>
</select>
Below is the input type to display the values after the calculation
<input type="text" name="cpp" id="cpp" value="10.95" class="form-control" maxlength="14" readonly>
<b>Currency Code</b>
</div>
<div class="col-sm-7">
<input name="tamount" type="text" id="tamount" value="10.95" class="form-control" readonly>
<b>Currency Code</b>
<span class="tamount"></span>
</div>
Below is the script to do calculations and to make changes onselect
<script type="text/javascript">
function caltotal() {
var x = document.getElementById("urgency").value;
if (document.getElementById("urgency").value == 'u') {
var u = 10.95;
document.getElementById("cpg").value = +u;
document.getElementById("ta").value = +u;
document.getElementById("np").value = +u;
} else if (document.getElementById("urgency").value == 'u') {
var u = 11.95;
document.getElementById("cpg").value = +u;
document.getElementById("ta").value = +u;
document.getElementById("np").value = +u;
} else if (document.getElementById("urgency").value == 'u') {
var u = 12.95;
document.getElementById("cpg").value = +u;
document.getElementById("ta").value = +u;
document.getElementById("np").value = +u;
}
</script>
The results that I expecting that when select urgency is selected the affects the display likewise the rest of selects.
There are a few things here that are not right with your code.
The if in your foreach loop prints the same result regardless of the
$row['idurgency'] making it redundant.
Option tags do not need an id attribute, and may even be causing the
problem. The id attribute should be unique and only assigned once per page.
Then some of your javascript is redundant as well.
function caltotal() {
var urgency = document.getElementById("urgency").value;
var amount;
if (urgency == 'u') {
amount = 10.95;
} else if (urgency == '?') {
amount = 11.95;
} else if (urgency == '??') {
amount = 12.95;
}
document.getElementById("cpg").value += amount;
document.getElementById("ta").value += amount;
document.getElementById("np").value += amount;
}
Just make sure you have only one element on the page that has one of the three names, cpg, ta, np.
I would advise you use more descriptive names for your variables it will help you in the long run.

how to rest dynamic text box value when rest button click

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

Add to database array of input fields generated with JavaScript

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.

getting select box to display selected value in different select box

I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.

Getting a Dynamically generated ID

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);
});

Categories