I have one Button that duplicates this line to choose more products.
My Html:
<td>
<input type="hidden" class="cod_linha" name="cod_linha[]"style="width: 100%;" />
<input type="text" name="linha[]" class="linha" style="width: 100%;" />
</td>
The problem is, I have two functions that find the product and other that Fill all the fields that I want automatically, what I have to do to differ this filled field of the empty field ? I tried this:
var table = $('#tabelaPedido');
$(table).each(function() {
if($(this).find('input.linha').val()=== ''){
Executes my function to fill the fields and to add a new line.
}
else{ }
And this too :
var counter = $(table).find("input.linha").length;
for(var i =0; i < counter; i++){
if($(table).find('input.linha').eq(i).val()== ''{}
But those codes don't fill the other empty line. see the imagem :
My code to fill the fields :
function preencherCamposProduto(obj) {
var table = $('#tabelaPedido');
$(table).each(function() {
if($(this).find('input.linha').val()=== '' &&
$(this).find('input.ref').val()=== '' &&
$(this).find('input.material').val()=== '' &&
$(this).find('input.cor').val()=== '' &&
$(this).find('input.descricao_marca').val()=== ''){
$.ajax({type: "POST",
url: '/pedidoOnline/index.php/Pedidos/pesquisarCamposProduto',
async: false,
data: {
cd_cpl_tamanho: obj
},
dataType: 'json',
success: function(data) {
var linhaId = data[0].idLinha;
var linhaLabel = data[0].labelLinha;
var refId = data[0].idRef;
var refLabel = data[0].labelRef;
var corId = data[0].idCor;
var corLabel = data[0].labelCor;
var marcaId = data[0].idMarca;
var marcaLabel = data[0].labelMarca;
var materialId = data[0].idMaterial;
var materialLabel = data[0].labelMaterial;`
var table = $('#tabelaPedido');
$(table).each(function() {
$(this).find('input.cod_linha').val(linhaId);
$(this).find('input.linha').val(linhaLabel);
$(this).find('input.cod_ref').val(refId);
$(this).find('input.ref').val(refLabel);
$(this).find('input.cod_material').val(materialId);
$(this).find('input.material').val(materialLabel);
$(this).find('input.cod_cor').val(corId);
$(this).find('input.cor').val(corLabel);
$(this).find('input.id_marca').val(marcaId);
$(this).find('input.descricao_marca').val(marcaLabel);
});
}
});
chamaAdicionarCampo();
}else{
console.log('Entrei no else');
}
});
}
Thanks a lot.
I've read your code and wrote a sample code in jsfiddle, that does things that you are writing about. In my solution I use CSS selector #tabelaPedido tr:last to select the last added row, and then write values to fields in this row.
Hope this helps.
The following simple jquery solution may help you:
$(document).ready(function(){
$('.linha').each(function(){
if ($(this).val() == ''){
//Call Your fill input function $(this) as parameter
}
});
});
Checkout This DEMO
With the answer of #zegoline and #semsem I figure it out.. Now it's working ! I added $( "tr:last" ).find() to every field on my each function and the #table tr:last too... Thanks a lot !
Related
I am trying to add an ability to change the contents of one of the columns in the data table (its data cells should be editable). I was using this tutorial as a reference:
https://www.youtube.com/watch?v=LbhVVN5ffi0
its source code:
https://github.com/divanov11/table-edit-backend
And so, I have the following functions in my template:
function edit_description(place){
var targetId = $(this).attr("id");
var value = $(this).text();
var targetIN = $(this).attr("identificationNumber");
$(this).unbind();
$(this).html(`<input class="description form-control" data-target="${targetId}" type="text" value=${value}>`);
$(`.description`).on('keypress', function(e){
if (e.which == 13) {
var target = $(this).attr("data-target");
var description = $(`#${target}`).text($(this).val());
save_description(description, targetIN);
return false;
}
})
}
function save_description(description, identification_number){
console.log('Saved!');
var user_input = {"identificationNumber":identification_number, "description":description};
update_description_POST(user_input);
}
After typing in for example "chipset" I get the following description's value:
<td identificationnumber = "1234" id="description-1234">chipset</td>
I would need the description's value to be just "chipset". How to achieve that?
EDIT: SOLVED. Thanks everyone!
I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!
$(document).ready(function() {
var anchors = document.getElementsByClassName('editButton');
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div>
Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.
So your final code should be something like this:
$(document).ready(function() {
$('.editButton').click(function() {
console.log('innerHTML is:', $(this).html())
console.log('id is:', $(this).attr('id'))
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(this).value;
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
<button class="editButton" id="firstButton">button 1</button>
<button class="editButton" id="secondButton">button 2</button>
<button class="editButton" id="thirdButton">button 3</button>
<button class="editButton" id="fourthButton">button 4</button>
</div>
save the button with button = this when run the onclick function and use it
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
var button;
var anchor = anchors[i];
anchor.onclick = function() {
button = this;
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+ button.value +'</p><br>';
$("#records").html(string);
});
}
}
});
https://jsfiddle.net/x02srmg6/
You need to look in to JavaScript closures and how they work to solve this.
When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.
One simple way to resolve this issue is listed below.
<div id="records"></div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var anchors = document.getElementsByClassName('editButton');
for(var i = 0; i < anchors.length; i++) {
//Wrap the function with an IIFE and send i value to the event listener
(function(anchor){
anchor.onclick = function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function( data ) {
var id = anchor.value;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
})(anchors[i]);
}
}
});
You can read more about this in JavaScript closure inside loops – simple practical example
In your code..
var id = anchor.value;
could be
var id = anchor.id;
but I recommend you to use event delegation
If you have a html like this
<div id="buttonArea">
<a class="editButton" id="1"/>
<a class="editButton" id="2"/>
<a class="editButton" id="3"/>
.......(so many buttons)
</div>
you can code like below.
$(document).ready(function(){
$('#buttonArea').on('click', 'a.editButton', function (event) {
var anchor = event.currentTarget;
$.ajax({
method: "GET",
url: "/testedit.php",
})
.done(function(data) {
var id = anchor.id;
/* from result create a string of data and append to the div */
var result= data;
var string='<p>ID is '+id+'</p><br>';
$("#records").html(string);
});
}
You can use getAttribute. Like:
var anchors = document.getElementsByClassName('editButton');
// Id of anchors
id_of_anchor = anchors.getAttribute("id");
Refs
EDIT
anchor.onclick = function() {
id_of_anchor = $(this).attr("id");
});
You have jQuery in your application, there is easier and more readable way to do it with jQuery;
$(document).ready(function() {
$(".editButton").each(function(a, b) {
$('#' + $(b).attr('id')).on('click', function() {
$.ajax({
method: "GET",
url: "/testedit.php",
}).done(function(data) {
var id = $(b).attr('id');
/* from result create a string of data and append to the div */
var result = data;
var string = '<p>ID is ' + id + '</p><br>';
$("#records").html(string);
});
});
});
});
Example: https://jsfiddle.net/wao5kbLn/
the below code works great for displaying in my first file
$.ajax({
url : "http://localhost/website/files/userstuff/files/",
asynch : false,
cache : false,
success: function (data) {
$(data).find("a").each(function(i, el) {
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("#filestable").html(displayfilestable)
$("filestable, table").append(adddata);
console.log(adddata)
}
});
}
});
this code will as you would think pull and display the files in the table row, however it is only performing this for the first file it finds I was wondering if anyone here could help get this to display all of the files in the files folder in the table. thanks in advance
enter image description here
Your code just works fine. The problems is, in that loop (each) you keep re-create table. That why it show only 1 data. Check my example based on your code.
HTML
<div>
sad1.pdf<br>
sad2.pdf<br>
sad3.pdf
<div id="filestable"></div>
</div>
JAVASCRIPT
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
$("#filestable").html(displayfilestable);
$("DIV").find("a").each(function(i, el) { // this is your data
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("filestable, table").append(adddata);
console.log(adddata)
}
});
AND Jsfiddle here :https://jsfiddle.net/synz/yrag1zpr/
I know some php/html/css but javascript is where I need help. I found on web autocomplete script, but this doesn't work on more than two input fields.
There are two problems I need to solve.
When you type in first box, autocomplete shows in second one. How to make script show autocomplete on box where user is typing?
I need to use the same autocomplete on multiple fields on my site.
The javascript syntax I use is:
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "http://example.com/autofill/auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})
$('.item').click(function() {
var text = $(this).html();
$('#keyword').val(text);
})
});
} else {
$('#results').html('');
}
});
$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});
});
In order to re-use the same autocomplete code you need to give the scope of the function the context of the correct DOM element.
Here's a a quick jsfiddle with some simple HTML code, but it should give a basic example of how to bind the same events to multiple dom structures.
DEMO: JSfiddle example
JS
var MIN_LENGTH = 2;
$(document).ready(function() {
$(".keyword").keyup(function() {
var $parent = $(this).parent();
var $results = $parent.find('.results');
var keyword = $(this).val();
if (keyword.length >= MIN_LENGTH) {
$.get("/echo/json/", {
keyword: keyword
})
.done(function(data) {
$results.html('');
data = ['test', 'test2'];
//data = jQuery.parseJSON(data);
$(data).each(function(key, value) {
$results.append('<div class="item">' + value + '</div>');
});
});
} else {
$results.html('');
}
});
});
HTML
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
<div class="autcomplete">
<input class="keyword" />
<ul class="results"></ul>
</div>
I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
if ($('#checkbox_' + id).is(':checked')) {
$('#' + id).addClass("selected");
}
else {
$('#' + id).removeClass("selected");
}
}
But, I don't know where to go from there.
Here is some example markup for one of the lines [generated by PHP] of the list of messages:
<div class="line" id="33" >
<span class="inbox_check_holder">
<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />
<span class="star_clicker" id="star_33" onclick="addStar(33)" title="Not starred">
<img id="starimg_33" class="not_starred" src="images/blank.gif">
</span>
</span>
<div class="line_inner" style="display: inline-block;" onclick="readMessage(33, 'Test')">
<span class="inbox_from">Nathan</span>
<span class="inbox_subject" id="subject_33">Test</span>
<span class="inbox_time" id="time_33" title="">[Time sent]</span>
</div>
</div>
As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {
}
else {
alertBox('No messages selected.'); //this is a custom function
}
});
I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!
How about this
$('#delete').click(function() {
var checked = $('.inbox_check:checked');
var ids = checked.map(function() {
return this.value; // why not store the message id in the value?
}).get().join(",");
if (ids) {
$.post(deleteUrl, {idsToDelete:ids}, function() {
checked.closest(".line").remove();
});
}
else {
alertBox('No messages selected.'); // this is a custom function
}
});
Edit: Just as a side comment, you don't need to be generating those incremental ids. You can eliminate a lot of that string parsing and leverage jQuery instead. First, store the message id in the value of the checkbox. Then, in any click handler for a given line:
var line = $(this).closest(".line"); // the current line
var isSelected = line.has(":checked"); // true if the checkbox is checked
var msgId = line.find(":checkbox").val(); // the message id
var starImg = line.find(".star_clicker img"); // the star image
Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
var result = null;
var scriptUrl = './databaseDelete.php';
$.ajax({
url: scriptUrl,
type: 'post',
async: false,
data: {id: reference_id},
success: function(response)
{
result = response;
}
)};
return result;
}
$('.inbox_check').each(function(){
if ($(this).is(':checked')){
var row = $(this).parent().parent();
var id = row.attr('id');
if (id == null)
{
alert('My selector needs updating');
return false;
}
var debug = 'Deleting ' + id + ' now...';
if (console) console.log(debug);
else alert(debug);
row.remove();
var response = removeDatabaseEntry(id);
// Tell the user something happened
$('#response_div').html(response);
}
});