I have a table that I get from my MySQL base using ajax. The answer from ajax makes the table in a DIV wrapper.
Now I need to edit this table and if it is needed to save it, but I've got several problems.
My plan was to make a $('td').click() append an input and after pressing enter or clicking anywhere the input should be hidden and the clear TD with new value should appear. After that I presss the UPDATE button and save my row to DB.
But my JavaScript skills are not so good and I failed even with 100 of examples.
Here is my code:
$('#load').click(function() {
//the load button - gets the table from DB
//here I get some data from the website filter.
var data = new webmaster(pid, name, email, skype, web, current_offer, lookingfor_offer, anwsered, comment);
data = JSON.stringify(data);
$('#aw-wrapper').empty();
$.ajax({
type: "POST",
data: {
"data": data
},
url: "inc/load-web.php",
success: function(anwser) {
$('#aw-wrapper').html(anwser);
TableEdit();
}
});
});
function TableEdit() {
if (i) {
$('td').click(function() {
this.onclick = null;
var td_value = $(this).html();
var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
$(this).empty().append(input_field);
$('input').focus();
i = 0;
});
}
}
But it doesnot work at all. I got many clicks on td instead of one. Maybe I am doing it wrong and it can be realized easier?
I dont see where i is defined. I changed your function to look like this:
function TableEdit() {
var i = 1;
$('td').click(function() {
if (i) {
this.onclick = null;
var td_value = $(this).html();
var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
$(this).empty().append(input_field);
$('input').focus();
i = 0;
}
});
}
if I understand what you want i believe it gives the desired result, however, this is how i would implement this
function TableEdit() {
$('td').click(function() {
var td_value = $(this).html();
var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
$(this).empty().append(input_field);
$('input').focus();
$('td').off('click');
$(this).find('input').blur(function(){
var new_text = $(this).val();
$(this).parent().html(new_text);
TableEdit();
})
});
}
updated fiddle https://jsfiddle.net/vf2L78p8/2/
Related
I try to dynamically add an input field to a form. It works fine except one thing:
I try to fill a with $.each, but this only works for the first dynamically added if I add more, the stays empty..
the #add button is in the initial form:
append:
$('#add').click(function() {
i++;
$dynamic_field').append('' +
'<h1>Sensor '+i+'</h1> ' +
'<tr id="row'+i+'">
'<td><div class="form-group">\n' +
'<label for="InputSensorType">Sensor Type*</label>\n' +
'<select class="form-control" id="InputSensorType" name="sensorType[]"></select>\n'
'</div></td>\n +'
'<td>
<button type="button" name="copy" id="copy" class="btn btn-primary">Copy this sensor
</button></td><tr>');
Each:
var jsarray = <?php echo json_encode($sensors)?>;
$.each(jsarray, function (index, value) {
$('#InputSensorType').append(('<option value='+index+'>'+value+'</option>'));
});
Can anyone help me?
Try this
var jsarray = '<?php echo json_encode($sensors)?>';
var obj = jQuery.parseJSON(jsarray);
var data = '';
$.each(jsarray, function (index, value) {
data +='<option value='+index+'>'+value+'</option>';
});
$('#InputSensorType').append(data);
I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?
<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();
SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions
Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});
In my program there is a table where a user can add customers and gets shown information about them. For this example the table consists of 3 rows with an input field. Adding those table rows, works.
In the first step, he should fill in the name of the customer and gets suggestions from jQuery UI Autocomplete. Works fine too.
Now the problem: When the name is filled in, an Ajax-Call gets data about the customer from a controller, the delievered data is correct. Now this data should be displayed in the input fields for that customer and that is where problem starts. I could only make it work for the next table row that directly follows, so in this case the ID is put in the right input field, but I have no Idea how to do that for the adress input field or later even more input fields and table rows.
Here is an example how it should work: First customer is John (ID: 1, Adress: Street 1) the table should look like this and work the following way:
Customer: John (via Autocomplete)
ID: 1 (Data from Ajax-Call and put in in this input field)
Adress: Street 1 (Data from Ajax-Call and put in in this input field)
Here is my HTML-Markup from the View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "")
<table id="customers">
<tr>
<td>Name of Customer:</td>
<td><input type="text" class="customername" id="customername-0" name="customername[0]" placeholder=""></td>
</tr>
<tr>
<td>ID of Customer:</td>
<td><input type="text" class="customerid" id="customerid-0" name="customerid[0]" placeholder=""></td>
</tr>
<tr>
<td>Adresss of Customer:</td>
<td><input type="text" class="customeradress" id="customeradress-0" name="customeradress[0]" placeholder=""></td>
</tr>
</table>
<button class="" type="button" id="add-customer" name="add-customer" onclick="add_customer()">Add another Customer</button>
</div>
}
JavaScript for adding table rows (not the most elegant way, I know):
<script>
// An array to store the ids of the customers
var customerIDArray = new Array();
customerIDArray.push("");
// An array to store the names of the customers
var customerNameArray = new Array();
customerNameArray.push("");
// An array to store the adresses of the customers
var customerAdressArray = new Array();
customerAdressArray.push("");
AutoCompleteCustomerName();
AutoCompleteCustomerID();
function add_customer() {
refresh_customerNameArray();
refresh_customerIDArray();
customerNameArray.push("");
customerIDArray.push("");
refresh_table();
}
function refresh_customerNameArray() {
for (i = 0; i < customerNameArray.length; ++i) {
customerNameArray[i] = $("#customername-" + i).val();
}
}
function refresh_customerIDArray() {
for (i = 0; i < customerIDArray.length; ++i) {
customerIDArray[i] = $("#customerid-" + i).val();
}
}
function refresh_customerAdressArray() {
for (i = 0; i < customerAdressArray.length; ++i) {
customerIDArray[i] = $("#customeradress-" + i).val();
}
}
function refresh_table() {
var htmlMarkup = '<table id="customers">'
if (customerNameArray.length == 1) {
htmlMarkup +=
'<tr>'+
'<td>Name of Customer:</td>'+
'<td><input type="text" class="customername" id="customername-0" name="customername[0]" placeholder="" value="' + customerNameArray[0] + '"></td>' +
'</tr>'+
'<tr>'+
'<td>ID of Customer:</td>'+
'<td><input type="text" class="customerid" id="customerid-0" name="customerid[0]" placeholder="" value="'+ customerIDArray[0] +'"></td>'+
'</tr>'+
'<tr>' +
'<td>Adresss of Customer:</td>' +
'<td><input type="text" class="customeradress" id="customeradress-0" name="customeradress[0]" placeholder=""></td>' +
'</tr>'
}
else {
for (var i = 0; i < customerNameArray.length; i++) {
htmlMarkup +=
'<tr>' +
'<td>Name of Customer:</td>' +
'<td><input type="text" class="customername" id="customername-' + i + '" name="customername['+ i +']" placeholder="" value="' + customerNameArray[i] + '"></td>' +
'</tr>'+
'<tr>' +
'<td>ID of Customer:</td>' +
'<td><input type="text" class="customerid" id="customerid-' + i +'" name="customerid['+ i +']" placeholder="" value="' + customerIDArray[i] + '"></td>' +
'</tr>'+
'<tr>'+
'<td>Adresss of Customer:</td>'+
'<td><input type="text" class="customeradress" id="customeradress-' + i + '" name="customeradress['+ i +']" placeholder=""></td>'+
'</tr>'
}
}
htmlMarkup +=
'</table>'
$("#customers").html(htmlMarkup);
AutoCompleteCustomerName();
AutoCompleteCustomerID();
}
</script>
My autocomplete-function:
<script>
function AutoCompleteCustomerName() {
$(".customername").autocomplete({
source: "/Home/AutoCompleteCustomerName",
select: function(event, ui) {
}
});
}
</script>
The Ajax-Call and the current solution for the next table row:
<script>
function AutoCompleteCustomerID()
{
$('.customername').on('focusout', function () {
var $id = $(this).closest("tr").next().find(".customerid");
var self = $(this);
$.ajax({
type: "GET",
url: "/Home/AutoCompleteCustomerID",
data: { name: $(self).closest("tr").find(".customername").val()},
contentType: "application/json",
dataType: "json",
success: function (result) {
$id.val(result.id);
}
})
});
}
</script>
So I would be thankful if you could give me an advice or a hint how this could be solved, Im pretty new to JavaScript and jQuery and still have to learn a lot.
I'm not sure it is what you need, you can try with this
var $street = $($id).closest("tr").next().find(".customeradress");
And so on with other fields which go in next lines.
NB I suppose that the related table rows are already in the page when you call the autocomplete, it seems like that.
So your autocomplete may become
<script>
function AutoCompleteCustomerID()
{
$('.customername').on('focusout', function () {
var $id = $(this).closest("tr").next().find(".customerid");
var $street = $($id).closest("tr").next().find(".customeradress");
var self = $(this);
$.ajax({
type: "GET",
url: "/Home/AutoCompleteCustomerID",
data: { name: $(self).closest("tr").find(".customername").val()},
contentType: "application/json",
dataType: "json",
success: function (result) {
$id.val(result.id);
$street.val(result.street);
}
})
});
}
</script>
Another approach would be working with data attributes and id depending on those but this may change a lot your scripts.
So I know there are a few posts about this but I haven't found them to helpful so I'm hoping this will shed new light on my problem.
I'm trying to to get data from a check-boxed row in a HTML table. At the moment I only want to display it on a windows.alert or in the Visual Studio console. But eventually I'm going to post the data to a database.
My code:
$(document).ready(function () {
$('#button').click(function () {
var id = [];
$(':checkbox:checked').each(function (i) {
id[i] = $(this).val();
});
if (id.length === 0) {
alert("Please select at least one checkbox");
}
else {
$.post('http://localhost/Dynamic/?Insert');
}
});
});
I've tried alert($(this).text()) but that just appears empty.
Help would be appreciated.
If it helps this is how I populate the table:
var tableName = 'table1'
$.ajax({
url: 'http://localhost/Dynamic?prod=' + tableName,
dataType: 'Json',
success: function (Results) {
$.each(Results, function () {
var row = "";
for (i = 0; i < this.length; i++) {
var input = '<td>' + this[i] + '</td>';
row = row + input;
}
$('#table1 tbody:last-child').append('<tr>' + row + '<td> <input class="checkBox" type="checkbox" id="count"/> </td></tr>');
});
}
});
As you can see the table is populated dynamically so it can be populated by different tables.
your selector is wrong. $(':checkbox:checked') should be $('.checkbox:checked').
maybe try to change to different class name.
$('.mycheckbox:checked').each(function (i) {
id[i] = $(this).val();
});
I've gotten it to work, I created a global array and added all the values to that. I then created a counter and set each checkbox's ID to the counters value. I then increment the counter before looping back around to sort with the next row of data.
Then When I want to choose data. I check the checkbox's of the data. Press the button then I get the Id's of each of the checkbox's. I then put the checkbox id into the array to get the value before adding it to an array which I then post.
I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});