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
Related
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.
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();
Below is the current script:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/Home/NewPopulation',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
var tr;
console.log(data);
for (var i = 0; i < data.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td style='display: none'>" + data[i].PollSurveyID + "</td>"
tr = tr + "<td>" + data[i].PollSurveyName + "</td>";
tr = tr + "<td>" + data[i].PollSurveyDescription + "</td>";
tr = tr + "<td>" + data[i].CategoryName + "</td>";
tr = tr + "<td>" + data[i].StartDate + "</td>";
tr = tr + "<td>" + data[i].EndDate + "</td>";
tr = tr + "<td><a class='editRow' ><i class='fa fa-edit'></i></a></td>";
//tr = tr + "<td><input type='button' id='btnDelete' value='Delete' /><i class='fa fa - close'></i></td > ";
tr = tr + "<td><a class='delRow'><i class='fa fa-trash'></i></a></td>";
tr = tr + "</tr>";
}
$('#tblPopulation').append(tr);
tblFormate();
},
error: function (xhr) {
alert('No Valid Data');
}
});
$('#tblPopulation').on('click', '.delRow', function () {
var table = $('#tblPopulation').DataTable();
table
.row($(this).parents('tr'))
.remove()
.draw();
});
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById("#tblPopulation").deleteRow(i);
}
function tblFormate() {
var table = $('#tblPopulation').DataTable(
{
//"searching": false,
"lengthMenu": [[5, 10, 50, 100, 150, -1], [5, 10, 50, 100, 150, "All"]]
});
//Apply the search
table.columns().eq(0).each(function (colIdx) {
$('input', table.column(colIdx).header()).on('keyup change', function () {
table
.column(colIdx)
.search(this.value)
.draw();
});
});
}
});
</script>
This is JavaScript for my datatable having edit and delete buttons. For edit I tried many thing but didn't get response from the button. What I want is when I click edit button all details must get filled in below sections individually. Except the Name other controls are dropdown so that user can change the category or status.
My thought of doing so was to take a hidden column and take PollId in that column when I click edit button of a row PollId would be sent to a hidden textbox. Based on the textbox value all controllers get populated as I have a function which take PollId as a parameter and returns all the details against that Poll or survey.
Any other idea are welcomed. Attaching a picture of page to give a rough idea of flow.
[
I have following code. Now I want to get the hidden column value based on user selected row. I also want to highlight the entire row, not only the e.target.
Can someone please help me.
function getTermdetailsQuerySuccsess(sender, args) {
var listEnumerator = Termsitems.getEnumerator();
var datatable = document.getElementById("TermList");
while (listEnumerator.moveNext()) {
var oListItem = listEnumerator.get_current();
//var firstName = listEnumerator.get_current().get_item('Title');
//var secondName = listEnumerator.get_current().get_item('LastName');
var termID = listEnumerator.get_current().get_item('ID');
var startdate = listEnumerator.get_current().get_item('startdate');
var enddate = listEnumerator.get_current().get_item('Enddate');
var termtype = listEnumerator.get_current().get_item('TermType');
var Hours = listEnumerator.get_current().get_item('Hours');
var EdNone = listEnumerator.get_current().get_item('EdNoned');
var Specialty = listEnumerator.get_current().get_item('Specialty');
var Subspecialty = listEnumerator.get_current().get_item('Subspecialty');
var Hospital = listEnumerator.get_current().get_item('Hospital');
var DEMT = listEnumerator.get_current().get_item('DEMT');
var Supervisor = listEnumerator.get_current().get_item('Supervisor');
rowcount = rowcount + 1;
$("#TermList").append("<tr style='border-bottom:1px silver solid' align='middle' class='gradeA'>" +
"<td align='left' style='display:none'>" + termID + "</td>" +
"<td align='left'>" + startdate + "</td>" +
"<td align='left'>" + enddate + "</td>" +
"<td align='left'>" + termtype + "</td>" +
"<td align='left'>" + Hours + "</td>" +
"<td align='left'>" + EdNone + "</td>" +
"<td align='left'>" + Specialty + "</td>" +
"<td align='left'>" + Subspecialty + "</td>" +
"<td align='left'>" + Hospital + "</td>" +
"<td align='left'>" + DEMT + "</td>" +
"<td align='left'>" + Supervisor + "</td>" +
"</tr>");
}
}
$('#TermList').click(function (e) {
var tr = $(e.target).parent().index() ;
alert(tr);
alert($(e.target).text()); // using jQuery
// var Cells = tr.e.getElementsByTagName("td");
$(e.target).addClass('row-highlight');
var confirmationM = confirm("Do you want to edit this term deatils ?");
if (confirmationM == true) {
confirmation = "You pressed OK!";
}
else {
confirmation = "You pressed Cancel!";
$(e.target).removeClass('row-highlight');
}
});
$('#TermList').click(function (e) {
var tr = $(e.target).parent().index() ;
alert(tr);
alert($(e.target).text()); // using jQuery
// var Cells = tr.e.getElementsByTagName("td");
$(e.target).addClass('row-highlight');
var table = $("#TermList")[0];
var cell = table.rows[tr].cells[1];
alert(cell);
var confirmationM = confirm("Do you want to edit this term deatils ?");
if (confirmationM == true) {
confirmation = "You pressed OK!";
}
else {
confirmation = "You pressed Cancel!";
$(e.target).removeClass('row-highlight');
}
});
I have following code. Now I want to get the hidden column value based on user selected row. I also want to highlight the entire row, not only the e.target.
Can someone please help me.
You have a lot of ways to improve/optimize your code. For example, instead of calling $(e.target) each time, you should save it into a variable: var $target = $(e.target), same thing for listEnumerator.get_current(), why do you call it all the time when you saved the value into oListItem ?!
But anyway, it's not your question.
Instead of binding the full table, you could bind only the TD: $('#TermList').click(function (e) { becomes $('#TermList').on('td', 'click', function(e) {
Then, to find the row, you just need to do:
var $td = $(this); // here it's your selected cell
var $tr = $td.parent(); // here it's your selected row
$tr.addClass('row-highlight'); // highlight the row
And to find the value in the first cell:
alert($tr.find('td:first').text()); // return the value of the first cell
I hope it helps.
I wanted the user to enter any alphabet in a text field, when he/she clicks on the Find! button, it will go through my php file and find a list of words that start with that alphabet (of course it's only a limited amount of words). And I want to output it to a table, with 5 columns, each cell containing one word.
Something like this:
in my HTML:
<label>
Enter any alphabet:
<input name="alphabet" type="text" id="alphabet"></label>
<input type="button" value="Find!" id="goFind">
<table border="1" id="output">
</table>
and Javascript:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var bunchOfWords = function (data) {
var listOfWords = "";
if(!Array.isArray(data)) {
return false;
}
else {
for(i = 0; i < data.length; i = +5) {
listOfWords += "<tr><td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td></tr>";
}
}
};
$("#goFind").click(function () {
var theWord = $("#alphabet").val();
$("#output").html("Loading..."); //gives the user an indication that it's loading
$.getJSON("wordslookup.php", "startswith=" + theWord, listOfWords);
});
});
Can't seem to figure out what's wrong.
listOfWords is out of scope in $.getJSON also its not a function, you should pass bunchOfWords to $.getJSON instead. To put the data in the table simply replace the current inner html, $("#output").html(listOfWords);