please, is there any way to put content into element with not know id or class, but by it's attribute? I have somewhere on the page more of this twins:
<input id="someSpecialId" class="autocomplete"/>
<ul data-for="someSpecialId"></ul>
List can be anywhere on page, not next to input.
In jQuery I have this:
$(document).on('keyup', '.autocomplete', function() {
var sectionName = 'autocomplete';
var min_length = 2;
var inputID = $(this).attr('id');
var keyword = $(this).val();
var $output = // HERE I NEED TO PUT FOUND ELEMENT BY IT'S data-for = inputID
if (keyword.length >= min_length) {
$.ajax({
url: 'php/readDB.php',
type: 'POST',
data: {section: sectionName, keyword:keyword},
success:function(data){
$output.show();
$output.html(data);
}
});
} else {
$output.hide();
}
});
Do you have any ideas, please? Thank you very much for answer.
var $output = $('[data-for="'+inputID+'"]');
The attribute equals selector.
You can use selector attributes for this. In general they look like this: [attribute="value"]
In your case, you would use something like this:
$('ul[data-for="'+inputID+'"]');
These work both in CSS and jQuery. Here's a code snippet with an example for both:
$('[data-for="second_input"]').html("<li>Item</li>");
[data-for="second_input"] {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="first_input" />
<ul data-for="first_input"></ul>
<input type="text" id="second_input" />
</div>
<ul data-for="second_input"></ul>
Related
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/
I have tried javascript and JQuery. I know how to write the code to get the cell values from my first tab but the same function does not work on the other tabs on my webpage. It seems as if the table in my other tabs is just a view. I am new to javascript and JQuery so think I might be missing something easy. I have used ".on" in my click function and that doesn't help. Here is the Javascript code and JQuery code, both work by grabbing the cell value I click but only for the first tab:
JavaScript
init();
function init(){
addRowHandlers('customerTable');
}
function addRowHandlers(tableId) {
if(document.getElementById(tableId)!=null){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
var cid = '';
var name = '';
for ( var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
cid = table.rows[this.i].cells[0].innerHTML;
name = table.rows[this.i].cells[1].innerHTML;
alert('cid: '+cid+' name: '+name);
};
}
}
}
JQuery
$('#customerTable').find('tr').click(function() {
var $id = $(this).closest("tr")
.find(".custId")
.text();
var $name = $(this).closest("tr")
.find(".custName")
.text();
alert($name);
$('.defaultTextBox.text_custId:text').val($id);
$('.defaultTextBox.text_custName:text').val($name);
});
In the end my goal is to get the elements clicked and set the text in my text boxes to those values, which you can see I did in the JQuery, but it only works on my first page. I need the click in my table to work on all tabs. Thanks in advance!
Edit
<div id="removeCustomer" class="tabcontent">
<h3>Pick a customer to remove!</h3>
<div class="container">
<br />
<h2 align="center">Search here to find the customer you want to remove</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by name, phone number, email, or state" class="form-control" />
</div>
</div>
<br />
<div class="result"></div>
</div>
</div>
The "removeCustomer" id is one of the tabs. So I have multiple tabs using the same, "result", which I think is the problem I just do not know how to solve it. If I Left out "result" it would not generate a table.
Here is the JQuery which uses a php file to connect to my database and get my data. And this is what generates result.
JQuery
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetchCustomers.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('div.result').html(data);
}
});
}
$('input.form-control').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
Thanks again.
I tried for hours but could not find any solution.
Simplified my code looks like following.
PHP :
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
...
}
?>
JS :
$(document).ready(function(){
$("._submit").click(function(){
?? var _title = document.getElementById('_title'),
?? _file = document.getElementById('_file');
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('title', _title.value);
...
</script>
I don't know how to get the data by class. By ID it is working, but i can't use IDs, because there would be several same IDs because of the foreach loop.
Tried this as well without success:
var _file = document.getElementsByClassName('_file');
I hope somebody can help me.
Misch
You can wrap your elements in container div like
<?php
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<div class='container'>
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
</div>
}
?>
Then use .closest() to traverse up the container. After wards you simply use find to get the desired elements.
<script>
$(document).ready(function(){
$("._submit").click(function(){
var container = $(this).closest('.container');
var _title = container.find('._title'),
var _file = container.find('._file')[0];
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
data.append('title', _title.value);
//Rest of your code
});
});
</script>
Since you're using jquery you could use .each() function and class selector . to loop through all the element with same class :
$('.class').each(function(){
var input_value = $(this).val();
})
Since you have more than one field with class _title and _file you should pass them as array to Formdata() using array signs [] :
var data = new FormData();
$('._file').each(function(){
var _file = $(this).val();
data.append('SelectedFile[]', _file.files[0]);
})
$('._title').each(function(){
var _title = $(this).val();
data.append('title[]', _title);
})
Hope this helps.
One more thing you can do a bit same as #satpal
Wrap your code in a div element.
PHP:
foreach($db->query("SELECT id FROM news ORDER BY position ASC") as $row)
{
...
<div> <!-- wrapper -->
<input type="text" class="_title" >
Search: <input type="file" class="_file" >
<input type='button' class="_submit" value='Save' >
</div>
}
?>
Then try following code.
JS:
$("._submit").click(function(){
var title = $(this).siblings('._title').val();
var file = $(this).siblings('._file')[0].files[0];
var data = new FormData();
data.append('SelectedFile',file);
data.append('title', title);
});
The above code makes use of .siblings() function
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 !
JS doesn't see input ID(undefined). I have no idea why it doesn't work. I found many solutions in google, but it still doesn't work.
index.html :
<div ng-class="{'form-group has-success':checkValue(answer) == true,'form-group has-warning': checkValue(answer) == false}">
<input id="422"
maxlength="3"
type="Integer"
class="form-control"
style="width: 100px"
ng-model="answer"
ng-blue="checkValue(answer, id)">
</div>
$scope.checkValue = function(value, id) {
$scope.val = id;
console.log($scope.val);
if ($scope.val == value)
return true;
else
return false;
}
The console just shows:
undefined
with jquery:
(function($) {
$( document ).ready(function() {
var inputId = $('input').attr('id');
console.log(inputId)
});
})( jQuery );
with pure javascript:
var inputs = document.getElementsByTagName("input");
var inputId = inputs[i].id;
console.log(inputId);
You can get the ID by using the following code:
$('ELEMENT').attr('id');
You can also use this code for getting other attributes as class name etc.
You can get the ID by using the following code:
$('.form-control').attr('id');
You can get ID by following code:
var element_id = $("input[ng-model='answer']").attr("id"); //Here I am using other unique property of the element to get its attribute
You can also make use other property also or else you can make use of other Jquery selector like this
var element_id = $(".form-control").attr("id"); //This may give unexpected result if class name is repeated
or
var element_id = $("input.form-control").attr("id"); //This is more assuring way since, we are providing class name along with element name