Does toggleclass work with js generated html? - javascript

I'm generating html content using an ajax data. Here is my code:
$('.expand').click(function(){$(this).toggleClass('open')});
function Get_id(){
$.ajax({
url: "here is my url with api_key",
datatype: "json",
method: "GET", // Что бы воспользоваться POST методом, меняем данную строку на POST
success: displayJson
});
}
Get_id();
function displayJson(jsonData){
let result='';
console.log(jsonData['applications']);
for (let i in jsonData["applications"]) {
let goods ='<ul class=goods-container>'
for(let j in jsonData["applications"][i]["goods"]){
goods +='<li class="good">'+jsonData["applications"][i]["goods"][j].name+'</li>';
}
let endtime = '';
let o_num = '';
endtime += '<p>'+jsonData["applications"][i]["planDeliveryPeriod"].endDate.slice(11, 16)+'</p>';
goods += '</ul>';
result += '<div class=order-container><p>'+jsonData["applications"][i]["customId"]+'</p>'+endtime+'<div class="expand"></div></div>';
$(".output").html(result);
}
setTimeout(Get_id, 30000);
}
So toggleclass doesn`t work here with , but if i have this html structure without js, it does. So is my problem in generating the html in javascript?

change first line like this:
$('body').on('click', '.expand', function() {
$(this).toggleClass('open')}
});

In your code the first line you wrote will search for elements matching .expand and add event-listeners to them. But since the element doesn't yet exist when the statement is run, it won't add any listeners.
You either have to run the statement after the element gets added or add the event listener to the body and check if the target matched .expand.
Here is an example:
$(".test").on("click", printMethod.bind("Direct Listener 1"));
$("body").on("click", ".test", printMethod.bind("Body Listener"));
var newButton = document.body.appendChild(document.createElement("button"));
newButton.className = "test", newButton.textContent = "2";
$(".test").on("click", printMethod.bind("Direct Listener 2"));
function printMethod() {
console.log(String(this));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="test">1</button>

Related

How to access an array of input elements created with ajax and javascript and get those individual values

Here's my code and my problem:
HTML:
<tbody id="list"></tbody>
Javascript:
let suggest;
const name = $('#post input[name=name]');
const rating = $('#post input[name=rating]');
const postinputs = $('#form-submit');
const table = document.querySelector('#list');
$.ajax({
method: 'GET',
url: wpApiSettings.root+'top-list-route/my-top-list-get',
contentType: 'application/json; charset=utf-8',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
dataType: 'json',
success: ajaxResponse
});
function ajaxResponse(data) {
let str = [];
suggest = data;
for ( let i = 0; i < suggest.length; i ++ ) {
const name = suggest[i].name;
const rating = suggest[i].rating;
str += '<tr>';
str += `<td><input type="text" value=${suggest[i].name}></td>`;
str += `<td><input type="text" value=${suggest[i].rating}></td>`;
str += `<td><button type="button">Update</button></td>`;
str += `<td><button class="delete">Delete</button><input name="delete[]" type="hidden" value=${suggest[i].id}></td>`;
str += '</tr>';
}
table.innerHTML = str;
}
Essentially I need to access the code of this string:
str += `<td><button class="delete">Delete</button><input name="delete[]" type="hidden" value=${suggest[i].id}></td>`;
In particular, I need to access the value, which is dynamically added by javascript.
I tried:
$(table).add('.delete').click( function() {
var log = $('input[name="delete[]"]').val();
console.log(log);
}
But the result is always 2, which is the first value of the array obtained from the input array of that particular element.
How can I solve my problem?
I tried also to bind the element with an event (on):
$(document).on(click, 'input[name="delete[]"]', function() {
console.log(this.val());
}
But it doesn't return anything.
Your second solution, the $(document).on(input) one, is correct in principle except that your input is hidden, so you cannot click on it. The first one is almost right. It should look like:
$(table).find('.delete').click( function() {
var log = $(this).siblings('input[name="delete[]"]').val();
console.log(log);
});
The idea is that we bind the click handler on the button (".delete"), and in the handler we find the input (which we know is a sibling of the button).
There's probably another problem in your case, though: if you load the table elements dynamically after, they won't have the click handler bound. So you could go with a compromise:
$(document).on('click', '.delete', function() {
var log = $(this).siblings('input[name="delete[]"]').val();
console.log(log);
});

Real time Javascript filtering not working throws undefined [duplicate]

This question already exists:
My live string search always returns false when it tries to match with includes() [duplicate]
Closed 3 years ago.
I want the code to return items from the JSON when i write something in the search bar (getting data from JSON tested and working).
The code is supposed to go to the JSON, read the line of the JSON (object) and compare with the keyword to see if it contains the keyword. If it contains it will display in <li> the item. It is always throwing "undefined".
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<input type="text" placeholder="Search Users" id="filter_items"/>
<ul id="items-list">
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'crossDomain': true,
'method': "get",
'url': "products.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
// lets filters it
ul = document.getElementById("items-list");
input = document.getElementById('filter_items');
var filterItems = function(event, json){
keyword = input.value.toLowerCase();
var li = "";
for (var index in json)
{
for (var j in json[index])
{
var line = json[index][j];
var filtered_items = line.title.filter(function(lin){
lin = lin.title.toLowerCase();
return lin.title.indexOf(keyword) > -1;
});
}
}
li += "<li>"+filtered_items+"</li>";
ul.innerHTML = li;
}
input.addEventListener('keyup', filterItems);
</script>
</body>
</html>
The JSON
{
"items": [{
"title": "Express"
}, {
"title": "Unexpress"
}]
}
It is supposed to return items matching the keyword in real time.
UPDATE
JSON isn't passing as parameter into the function with event as parameter too. Anyone know how to solve it?
You aren't passing an additional variable to the function when you trigger the event, so it's unclear why you'd expect json to be populated.
But you don't need it anyway - the content of JSON doesn't change every time the event happens, the data is always the same. Just download it when your page loads, and then add the event listener when it's finished downloading, and use the function without the additional parameter. json can be declared global so it'll be in scope.
I think the code might make more sense like this:
var json = null;
$.ajax({
'global': false,
'crossDomain': true,
'method': "get",
'url': "products.json",
'dataType': "json",
'success': function (data) {
json = data;
input.addEventListener('keyup', filterItems);
}
});
ul = document.getElementById("items-list");
input = document.getElementById('filter_items');
var filterItems = function(event){
keyword = input.value.toLowerCase();
var li = "";
for (var index in json)
{
for (var j in json[index])
{
var line = json[index][j];
var filtered_items = line.title.filter(function(lin){
lin = lin.title.toLowerCase();
return lin.title.indexOf(keyword) > -1;
});
}
}
li += "<li>"+filtered_items+"</li>";
ul.innerHTML = li;
}
P.S. 'async': false is deprecated due to the poor user experience it creates (locking up the main browser UI during requests). Some browsers will issue a console warning when you try to use it. But there should be no need for it. You should aim to use callbacks/promises correctly instead. I removed it in my example above, and instead (for reliability) we don't add the event listener to the input box until the JSON download has completed. Hopefully it isn't too big a file.
P.P.S. If you ever find yourself swapping the static JSON file for a server-side script to retrive product data from a database, it would be advisable to change your code so that the filtering of data happens on the server - usually it's a lot more efficient to filter using a SQL query and return only the data which is truly needed, than to download everything and then filter it using JavaScript.
I belive the filtering part should be changed.
Maybe to something like the following?
var json = { "items": [{"title": "Express"}, { "title": "Unexpress"}] };
// lets filters it
ul = document.getElementById("items-list");
input = document.getElementById('filter_items');
var filterItems = (event) => {
keyword = input.value.toLowerCase();
var li = "";
var filtered_items = json.items.filter(function(lin){
return lin.title.toLowerCase() == keyword;
});
for ( var i in filtered_items ) {
li += "<li>"+filtered_items[i].title+"</li>";
}
ul.innerHTML = li;
}
input.addEventListener('keyup', filterItems);
<body>
<input type="text" placeholder="Search Users" id="filter_items"/>
<ul id="items-list">
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

I am trying to display ajax result in html but append() function displays raw html tags .

I am trying to display ajax result in html but append() function displays raw html tags .
success:function(result){
var element = document.createElement('div');
jQuery.each(result.data , function(key,value){
element.append('<div class="col-lg-6">'+value["name"]+'</div>')
});
$('.user-profile').html(element);
}
Any help!
Have you tried to simply add the content as html in your element ?
success:function(result){
var str = '';
jQuery.each(result.data , function(key,value){
str += '<div class="col-lg-6">'+value["name"]+'</div>';
});
$('.user-profile').html(str);
}
You've to explicitly create every element:
success:function(result){
var element = document.createElement('div');
jQuery.each(result.data , function(key,value){
var divElem = document.createElement('div');
divElem.className = 'col-lg-6';
divElem.innerHTML = value["name"];
element.appendChild(divElem);
});
$('.user-profile').html(element);
}
append method accepts node objects and DOMString . But, its specification has not been stabilized. It is better to use appendChild which accepts node object.
Since you're using jQuery it could be done like :
success:function(result){
var element = $('<div/>');
jQuery.each(result.data, function(key, value){
element.append( $('<div/>', {class: "col-lg-6",text: value["name"]}) );
});
$('.user-profile').html(element);
}
Hope this helps.

Javascript not recognizing a created button

I have some Javascript that creates a button when an ajax form submission is successful. When the page is reloaded the button will be rendered to the page.
Its a simple form javascript combination to add an item to a table with a remove button to remove that item.
I've run a diff tool and there aren't any differences between submitting the form and creating the button, and reloading the page with the button already created. So that leads me to believe Javascript isn't recognizing the button being created.
Here is some code:
Here is my javascript method
$('button#proxy_remove_given').click(function() {
$.ajax({
url: $('button#proxy_remove_given').attr('action'),
type: 'POST',
data: $('form#proxy_submit_form').serialize(),
success: function(responce) {
if ("Success" == responce) {
var username = $('button#proxy_remove_given').attr('name');
$('#given_proxy_access_table tr#'+username).remove();
var table_length = document.getElementById("given_proxy_access_table").rows.length;
if (table_length == 0) {
var table = document.getElementById("given_proxy_access_table");
var new_row = table.insertRow(0);
new_row.id = "NoProxyRow";
var cell1 = new_row.insertCell(0);
var cell2 = new_row.insertCell(1);
cell1.innerHTML = "<p>No Proxies Found</p>";
cell2.innerHTML = "<button data-toggle=\"collapse\" data-target=\"#add\">Add</button>";
}
}
}
});
});
Here is the javascript to add the button
$('button#proxy_submit').click(function() {
$.ajax({
url:'proxy/submit',
type: 'POST',
data: $('form#proxy_submit_form').serialize(),
success: function(responce) {
if ("Success" == responce) {
var table = document.getElementById("given_proxy_access_table");
if (table.rows.length == 1) {
if (table.rows[0].id == "NoProxyRow") {
document.getElementById("given_proxy_access_table").deleteRow(0);
}
}
var username = document.getElementById('id_proxy_username').value
var new_row = table.insertRow();
new_row.id = username;
var cell1 = new_row.insertCell(0);
var cell2 = new_row.insertCell(1);
cell1.innerHTML = "<p>{0}</p>".replace(/\{0\}/g,username);
cell2.innerHTML = "<button type=\"submit\" name=\"{0}\" id=\"proxy_remove_given\" action=\"proxy/remove/given/{0}\">Remove</button>".replace(/\{0\}/g,username);
document.getElementById("proxy_submit_form").reset();
}
}
});
});
Any idea why javascript wouldn't recognize a button being created?
<button type="submit" name="MikeC" id="proxy_remove_given" action="proxy/remove/given/MikeC">Remove</button>
EDIT:
Why isn't this
$('button#proxy_remove_given').click(function()
picking up this
<button type="submit" name="MikeC" id="proxy_remove_given" action="proxy/remove/given/MikeC">Remove</button>
when I add the button to the page
but it picks up the button call when I reload the page
It sort of depends how your code is structured but I’m guessing your click listener wont find the button because it doesnt exist yet.
$('button#proxy_remove_given') looks for the button but it isn’t there yet. You should put your click listener after the button has been added.
if I got your point
1st: if you use submit form or button type submit click without reloading the page you can use e.preventDefault()
2nd: with dynamically generated elements you should use
$('body').on('click', 'selector' , function(){});
take a look at Event binding on dynamically created elements?

print array with js and add html with jQuery

i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.
HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/
Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});
First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);
It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}

Categories