on click funtion is not working in jquery - javascript

In following code i want to run a function when someone click on SELL button(first td) but on click function is not working. it says run function is not defined.
function runfunction() {
alert("success");
}
sendRequest(); //call function
function sendRequest() {
$.ajax({
type: "POST",
url: '<?php echo site_url("ajax/ajax_buybtc"); ?>',
success: function(result) {
var jsonResult = JSON.parse(result);
$(".tab1 tr.tr1").remove();
jsonResult.forEach(function(data) {
var newTr = ""; // I delete the value to avoid double tr declaration
newTr +=
'<tr class="tr1"> <td onclick="runfunction()" style="text-align:center;"><a><span class="label label-warning">Sell</span></a></td>';
newTr += "<td id='xbtc " + data.xbtc + "'>" + data.xbtc + "</td>";
newTr += "<td id='xbtc " + data.rate + "'>" + data.rate + "</td>";
newTr += "<td id='xbtc " + data.xpkr + "'>" + data.xpkr + "</td>";
newTr += "</tr>";
$(".tab1 > tbody:last-child").append(newTr);
});
setTimeout(function() {
sendRequest(); //this will send request again and again;
}, 4000);
},
});
}

try to add a click function after adding a class (here I added 'td-click') to the td and remove the onclick attribute from td
$(".tab1").on("click", ".td-click", function(){
alert("success");
})

You need to change onclick="runfunction()" to onclick="runfunction".
Currently what's happening is that the runfunction is executed, and its return value is bound to the onclick event. You want the function itself to be bound, not its return value.

newTr += '<tr class="tr1"> <td onclick="runfunction()" style="text-align:center;"><a><span class="label label-warning">Sell</span></a></td>';
move onclick to span tag
newTr += '<tr class="tr1"> <td style="text-align:center;"><a><span onclick="runfunction()" class="label label-warning">Sell</span></a></td>';
https://codepen.io/bot_3310/pen/JajYyY

Related

Calling a function in dynamically created button javascript

I'm trying to create a button with a an onClick that calls a function with the signature deleteEntry(entry). However, I get an error saying that entry is undefined even though I am using it in the same function. I tried adding escape characters but it does not have any effect. Any ideas?
function addToTable(entry) {
var result = "<tr>"
result += "<td>" + entry.id + "</td>";
result += "<td>" + entry.title + "</td>";
result += "<td>" + entry.url + "</td>";
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry +
")\">Delete</button></td>";
result += "</tr>";
$("#table").append(result);
}
You can create the button as a jQuery object and use the on method to listen to the click event. Then when the event listener is attached append the button to the row like the other elements in the function.
Check the code snippet below to see it in action.
// Dummy entry.
var entry = {
id: 0,
title: 'test',
url: 'http://url.com'
}
// Your AJAX call.
function deleteEntry(entry) {
console.log(entry);
}
function addEntryToTable(entry) {
var $id = $('<td>' + entry.id + '</td>');
var $title = $('<td>' + entry.title + '</td>');
var $url = $('<td>' + entry.url + '</td>');
var $button = $('<button class="btn">Delete</button>');
var $buttonWrap = $('<td></td>');
var $row = $('<tr></tr>');
// Add 'click' event listener to the button.
$button.on('click', function(event) {
deleteEntry(entry);
});
$buttonWrap.append($button)
$row.append($id, $title, $url, $buttonWrap);
$('#table').append($row);
}
addEntryToTable(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table"></table>
If you inspect this button you generated it will probably have the following attribute: onClick="deleteEntry([object Object])
I think what you want is:
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry.id + ")\">Delete</button></td>";
I guess you have a list variable "entries" somewhere.
In the delete function you can find the clicked entry with the inputed Id.

Empty Div tag issue for dynamically rendered table

I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();

Javascript input field value

Need to get the value of input field inside script tag.
I need to get a value of input field that append to the html table using script tag. My code is following
function myFunction(i) {
$.ajax({
url: "<?php echo base_url(); ?>admin/itemD",
type: "POST",
dataType: "json",
data: {
"itID": i
},
success: function(data) {
//console.log(data);
if (data[0].availability == 0) {
alert('Item Not Available');
} else {
var tr = "<tr>";
var td0 = "<td>" + (i + 1) + "</td>";
var td1 = "<td>" + data[0].item_name + "</td>";
var td2 = "<td>" + data[0].price + "</td>";
var td3 = "<td><input placeholder='Advance' class='form-control col-3' /></td>"
$("#myTable").append(tr + td0 + td1 + td2 + td3);
}
},
error: function(err) {
console.log(err);
}
});
}
This is my code I used this code to show some data set which get from clicking event. But now I need to add input field to my javascript code. So I add input field to my code.
var td3 = "<td><input placeholder='Advance' id='vale' class='form-control col-3' /></td>"
But how do I get this input field value?
I tried to get the value of this input field by adding
document.getElementById('vale');
But It does not work. I go though the every problem earlier posted in stackoverflow. But no problem matching with my problem.
One way to achieve this might be to update your success handler, by binding an event handler via say, keyup(), that queries the current value of the input field when a key is pressed while the field is focused:
success: function(data) {
//console.log(data);
if (data[0].availability == 0) {
alert('Item Not Available');
} else {
var tr = "<tr>";
var td0 = "<td>" + (i + 1) + "</td>";
var td1 = "<td>" + data[0].item_name + "</td>";
var td2 = "<td>" + data[0].price + "</td>";
var td3 = "<td><input placeholder='Advance' class='form-control col-3' /></td>"
$("#myTable").append(tr + td0 + td1 + td2 + td3);
}
// Select the input field for the table, and add a keyup event listener
// to it
$('input', '#myTable').keyup(function() {
// Access the current value of the field like so
var currentFieldValue = $('input', '#myTable').val();
alert( 'Value of input is: ' + currentFieldValue );
})
}
You need to add id='vale' attributes which is not available in your input tag
After that you can get value by like this:
document.getElementById('vale').value

How to dynamically create a radio button with ajax

I am pulling data and with ajax and displaying in a form. If a user clicks on any result returned from ajax, it updates an input field. Now instead of only displaying the names on the list, I want to include radio button alongside each name.
Here is my code.
$(function() {
$('#searchpartno').keyup(function() {
var item = $(this).val();
var item_value = $('#price_luitem_id').val();
$.ajax({
"url": "/searchpartno_stock",
"data": {"partnumber":item,"luitem_id":item_value},
"type": "get",
"dataType": "json",
"success": function(items) {
$('#partnumber_tbody').empty();
var clearHTML = '<tr>' +'<td></td>' +'</tr>';
var trHTML = '';
$.each(items, function (i, item) {
trHTML += '<tr>' +'<td onclick="updatePartNo(this)" class="partspare_list">' + item.partnum + '</td>' +'</tr>';
});
$('#partnumber_tbody').append(clearHTML);
$('#partnumber_tbody').append(trHTML);
},
"error": function() {
$('#dailysale_price').val('');
}
});
})
})
Here is the output
Instead of appending the partnum as a text , create a radio button the same way you create the tr and td
$.each(items, function (i, item) {
trHTML += '<tr>' +
'<td onclick="updatePartNo(this)" class="partspare_list">' +
'<input type="radio" name="itemnum" value="' + item.partnum
+ '">' + item.partnum + '<br>' +
'</td>' +
'</tr>';
});
Just add radio input like following :
$.each(items, function (i, item) {
trHTML += '<tr>
<td onclick="updatePartNo(this)" class="partspare_list">
<input type="radio" name="itemRd" value="'+i+'">
' + item.partnum + '
</td>
</tr>';
});

jquery remove everything after space

I am trying to remove everything in my string after space like so:
value.baseOrSchedStartList[i].substring(0, value.baseOrSchedStartList[i].indexOf(' '))
But I get this error:
Uncaught TypeError: Cannot read property 'substring' of undefined
What am I doing wrong ? This is inside an ajax call...here is the full ajax call:
$.ajax({
type: "GET",
url: "/vendorProject/api/connection/getVendorItems?community=" + $("#communtiyDropdown").val(),
dataType: 'json',
cache: false,
success: function (results) {
var html;
html = "<table border='1'>";
html += "<tr>";
html += "<th>Task</th>";
$.each(results, function (key, value) {
html += "<th>" + key + "</th>";
});
html += "<th></th>";
html += "</tr>";
for (i = 0; i < taskArray.length; i++) {
html += "<tr>"
html += "<td>" + taskArray[i] + "</td>";
$.each(results, function (key, value) {
html += "<td>" + value.baseOrSchedStartList[i].substring(0, value.baseOrSchedStartList[i].indexOf(' ')) + "</td>";
});
html += "<td><input type='checkbox' name='checkbox' id='checkbox' /></td>"
html += "</tr>";
}
html += "</table>";
$("#tableData").html(html);
}
});
The string in question is 12-12-2015 08:00:00 AM and I looking for 12-12-2015....no time.
Try to substr :)
$("button").on("click",function(){
var a = $("input").val();
var cropped = a;
if(a.indexOf(" ")>=0) cropped = a.substr(0,a.indexOf(" "));
$("b").html(cropped);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' placeholder='write something here and hit the button' style='width:60%;'>
<br>
<button>Ready!</button>
<br>
<div>
The result without space and after all : <b></b>
</div>

Categories

Resources