Here is my code:
$(".cbtn").click(function(e) {
alert("here");
var id = $(this).attr('id');
var comment = $('input[id$=id]').val();
alert("hay" + id);
alert(comment);
$.post("comments.php", {
id: id,
comment: comment
})
});
});
The id of cbtn and the text field is created dynamically like this:
<input type="text" class="enter_comment value="comments" id="comm<?php echo $row['p_id'];?>"/>
<input type="button" value="enter" class="cbtn" id="<?php echo $row['p_id'];>">
When cbtn is clicked, I want to get the id of text field that ends with the same id as cbtn. But it is returning undefined instead.
You need to concatenate the id variable in the selector, like this:
$(".cbtn").click(function(e) {
var id = this.id;
var comment = $('input[id$=' + id + ']').val();
$.post("comments.php", {
id: id,
comment: comment
})
});
Alternatively, as the id of the text field is the same as the checkbox, but with comm prepended, you could select it by id directly, which would be quicker:
var comment = $('#comm' + id).val();
Or, if the text field is always the element preceding the checkbox, you could negate the need to select by id completely and use the prev() method:
$(".cbtn").click(function(e) {
$.post("comments.php", {
id: this.id,
comment: $(this).prev().val()
})
});
Related
I have written the ajax for the static id. I want to convert it in dynamic id but I don't know how to convert it.
Here id is textbox1, I have textbox1 to textbox10 and rate1 to rate10 it generates dynamically. So how to do it?
$(document).on('change','#textbox1',function () {
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
$.ajax({
type:'get',
url:'{!!URL::to('search')!!}',
data:{'id':prod_id},
dataType:'json',//return data will be json
success:function(data){
console.log("price");
console.log(data.rate);
// here price is column name in products table data.coln name
a.find('#rate1').val(data.rate);
},
error:function(){}
});
});
Use class instead of id
Generate dynamic textbox with class attribute
<input type="text" name="prod_id" class="_my_textbox">
In js code:
$(document).on('change', '._my_textbox' ,function () {
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
$.ajax({
type:'get',
url:'{!!URL::to('search')!!}',
data:{'id':prod_id},
dataType:'json',//return data will be json
success:function(data){
console.log("price");
console.log(data.rate);
// here price is column name in products table data.coln name
a.find('#rate1').val(data.rate);
},
error:function(){}
});
});
Since you're using a select element, you could use the onchange prop and asign the function with the ids to it, so you can then use it in your js. The dynamic id would have to come from a PHP script like so:
$stmt = $DBcon->prepare("SELECT txtbx_id, role_id FROM your_table WHERE you_conditions_if_u_have_any");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $rows) {
$txtbx_id= $rows['txtbx_id'];
$role_id= $rows['role_id'];
echo '
<div class="card">
<select onchange="yourfunction('.$txtbx_id.', '.$role_id.')" >
....
</select>
</div>
';
}
Then in your js, instead of on document change, use the function with the ids as variables like so:
function yourfunction(textbox_id, role_id){
// use the ids which are affected in here
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
$.ajax({
type:'get',
url:'{!!URL::to('search')!!}',
data:{'id':prod_id},
dataType:'json',//return data will be json
success:function(data){
console.log("price");
console.log(data.rate);
// here price is column name in products table data.coln name
a.find('#rate1').val(data.rate);
},
error:function(){}
});
});
ok .. quick overview.
I have a table and each row has the ID attribute value assigned based on the ID form the db record
I have a click event that shows / hides a div and I want the data it displays
in that div to be based on the results from the DB for that corresponding ID value
Here is my table code showing the ID
<td class="hidden-xs">
<a data-toggle="toggle" href="#comp_info" class="showcompinfo" id="<?php echo $complistr['company_id'];?>">
<?php echo $complistr['registered_office_address'];?>
</a>
</td>
This is where I want the data displayed
<div class="panel-heading">
<i class="fa fa-building" style="color:orangered"></i>
<span id="showcompname"></span>
</div>
Here is the jquery code
$(document).ready(function () {
$('#comp_info').hide();
$('.showcompinfo').click(function () {
var id = $('.showcompinfo').attr('id');
$('#comp_info').toggle();
var companyid = id;
var dataString = 'companyid=' + companyid;
$.ajax({
type: 'POST',
url: '../inc/dataforms/complist.php',
data: dataString,
success: function (result) {
$('#showcompname').html(result);
}
});
});
});
Here is the PHP code for the query
include('../config.php');
if (!empty($_POST['companyid'])) {
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc, "SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if ($result) {
echo $result['name'];
}
}
Please dont say .. your code is open to SQL injection .. i've said before its on a closed system with no external access and the people using it can barly use a PC
All I want it to do is to display the company name in the showcompname span box
If possible am I also able to display different result data in different divs ?
To retrieve the ID from the clicked <a> tag, in your jQuery code change this line:
var id = $('.showcompinfo').attr('id');
For this one:
var id = $(this).attr('id');
That way you are retrieving the id attribute from the element that was the target of the click event.
Your original code was retrieving an array of ids of all elements with the class showcompinfo.
Your problem lies in the selector for the id, var id = $('.showcompinfo').attr('id');.
You are selecting every showcompinfo in the page.
You would be better off by using this in that selector.
This would correctly select your id, based off the clicked td.
var id = $(this).attr('id');
I am writing an ajax live search feature into my software. There are multiple input that need to be ajax searchable on each form. Everything works great except I want the list of results to be displayed in a hovering "p" element right below the input I am currently searching in. Right now I have a "p" with class = "options" right below each input to display the results. When I type, the results are displayed in EVERY "p", that is, hovering under every input. Is there a way to reference just the child of the current input or do I need to use a separate function explicitly referencing the desired for each input? I've tried a lot of child selector options on the internet and none of them have worked. The code is below. Thank you for your advice.
$(document).ready(function() {
//sets the chosen value into the input
$( ".options").on( "click", function(event) {
var item = $(event.target).text();
$('#acctname').val(item);//place chosed result into the acctname input
$('.options').hide();//hide result options after click
});
//On pressing a key in input field, this function will be called.
$(".textinput").keyup(function() {
var id = $(this).attr("id");
var val = $(this).val();
if (val === '') { //Validating, if "name" is empty.
$('div > p').html('').show();
}else {//If input is not empty.
$.ajax({
type: "POST",
url: "../model/ajax/livesearch.php",
data: {id: id, val: val},
success: function(html) {//place the result into the p element and set the proper css
$('div > p').html(html).show().css({"position":"absolute","z-index":"+1","cursor":"pointer","color":"black","background-color":"white"});
}
});
}
});
});
Update: this is how my HTML forms are structured.
<form action= "../model/dataentry.php?formname=enter_deposit" method="POST" id="ajaxform" name="ajaxform">
<div class = "label"><p1>Revenue Account Name</p1></div><div class = "field"><input class = "textinput" type="input" name="acctname" id="acctname" value = "" autocomplete="off">
<p class = "options"></p></div>
<div class = "label"><p1>Revenue Account Number</p1></div><div class = "field"><input class = "textinput" type="input" name="acctno" id="acctno" value = "" autocomplete="off">
<p class = "options"></p></div>
<input class = "submit" name = "Submit" type = "button" id = "ajaxsubmit" value = "Submit" >
<input class = "submit" name = "Close" type = "button" id = "close" value = "Close" >
</div>
</form>
Is this what you are looking for?
https://jqueryui.com/autocomplete/
I found a solution to the issue in case anyone is curious. By assigning each div with class "option" an id equal to its parent's id plus "_opt" (i.e. "acctname" input would have a child div with id "acctname_opt"), I can edit div ids dynamically in my functions to place the result list where I want it. Here is my new javascript code. Works flawlessly. Thanks for your help, everyone.
$(document).ready(function() {
//sets the chosen value into the input
$( ".options").on( "click", function(event) {
var item = $(event.target).text();
var clickedid = $(this).attr('id');
var targetid = clickedid.split('_'); //remove the '_opt' suffice to get the target id
$('#' + targetid).val(item);//place chosed result into the acctname input
$('.options').hide();//hide result options after click
});
//On pressing a key in input field, this function will be called.
$(".textinput").keyup(function() {
var id = $(this).attr("id");
var optid = id + '_opt'; //set the target element id
var val = $(this).val();
if (val === '') { //Validating, if "name" is empty.
$('#' + optid).html('').show();
}else {//If input is not empty.
$.ajax({
type: "POST",
url: "../model/ajax/livesearch.php",
data: {id: id, val: val},
success: function(html) {//place the result into the p element and set the proper css
$('#' + optid).html(html).show().css({"position":"absolute","z-index":"+1","cursor":"pointer","color":"black","background-color":"white"});
}
});
}
});
});
I want to pass the id into a string but always I get an error
var c = document.getElementById("predefinedMessage");
var id= c.selectedIndex;
var text= "{{ form.predefinedMessage.vars.choices[id].data.message }}";
$('message').val(text);
});
how I can pass the id in the text variable
If the element that you're selecting is a drop down list, I suggest the following code using jQuery as you're already using it:
// Select by the ID predefinedMessage
var dropDown = $("select#predefinedMessage");
// Get the selected index from the dropdown
var selectedIndex = dropDown.find("option:selected").index();
var text = "{{ form.predefinedMessage.vars.choices[" + selectedIndex + "].data.message }}";
$('message').val(text);
I have a table with a button that adds 5 rows with cells to the table when clicked. I want to bind an event to cells in the 5th column of the table. All of these cells are named "Count_" followed by the row number. So, the cell in Row 0 is:
<td name="CountCell_0">
<input type="text" name="Count_0">
</td>
And I'm trying to update the input with name Count_X (where X is the row number).
The binding works for the cells that existed on the page originally. However, the event is not triggering for cells that were added with the button.
Here is an example of a cell that was dynamically added:
<td>
<input type="text" name="Count_348">
</td>
Here is my Jquery event:
$(document).ready(
function() {
$(document).on('change','[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}
);
I think the problem was here [name^="Count_"]' you need a selector so change to this input[name^="Count_"]' and the anonimous function is not performed
$(document).ready(
(function() {
$(document).on('change','input[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}());
);
I moved the function outside of the document ready, and it now triggers on the dynamic rows.