Javascript not recognizing a created button - javascript

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?

Related

Does toggleclass work with js generated html?

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>

How to avoid appending duplicates on ajax after second call?

I have a button called File which is a dropdown that has another button called open. Once the user clicks open I have an ajax GET request that appends a button after each call.
When the user clicks open once, the button is appended. However, when the user clicks open again, the same button is appended again with the same attributes and if the user clicks the open button the third time the button is appended once more, so a total of three times.
How do I ensure the button is only appended once?
The {{}} is from the django web framework and is not a concern
<input type = "button" class = "openGraph" value = "{{titles}}" id="{% url 'openGraph' title=titles.id %}">
This is the occurence when the user presses the open button.
$(document).ready(function(){
$('#openXML').on('click',function(event){
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "GET",
url: "/loadTitles/",
dataType: 'text',
headers:{
"X-CSRFToken": csrftoken
},
success: function(data){
var json = JSON.parse(data)
var length = Object.keys(json).length
var pk = "/openGraph/" + json[length-1]['pk']
var title = json[length-1]['fields']['title']
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
$("#loadAllTitles").append(myButton)
}
});
})
});
Because the IDs must be unique I'd suggest to test if the button already exist before adding. Hence, you need to change this line:
$("#loadAllTitles").append(myButton)
with:
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
I get the following console error: Uncaught Error: Syntax error, unrecognized expression: #/openGraph/104 –
If you are using jQuery 3.x you need to use:
jQuery.escapeSelector(): Escapes any character that has a special meaning in a CSS selector.
UPDATE
While pk is the ID when you create a new element you add to this ID a final /. This is your issue.
$('button').on('click', function(e) {
var pk = '#/openGraph/104';
var title='title';
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="loadAllTitles">
</form>
<button type="button">Click to add the same input field</button>
Check for the presence of a button on line 3
$(document).ready(function(){
$('#openXML').on('click',function(event){
if (!$('#+pk+').length) {
// Your code
}
}
}

Duplication of rows in Javascript Table

I am quite new to javascript and for some time now i cant figure a solution to a problem that i have on my own. The web application i am building is using javavascript and Firebase. I am creating a table that pulls some data from mysql and display them as a table in my website. The table consists of three columns ID,NAME, AND SURNAME.Along with that i am also creating a new column called Recipient that consists of buttons. The table looks like this:
I give a different value to each of the buttons, the value of each button is the number of the ID that is in the same row as the current button. For example the first button has a value = 2, the 3rd a value = 123. Al the buttons have an id = contact
The source code of the table is
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName`,`storagefolder` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table class=table table-condensed>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Recipient</th>
</tr>
</thead>";
while($record = mysql_fetch_array($clients)){
echo "<action=usersfiles.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<button value=".$record['ID']." id=contact>Folder Data</button>"." </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
When i click on a button from the table the application get the value of the corresponding button and store it in a variable, then it sends the variable to a function that will drug all the files from firebase database that are store in the folder with the same name as the variable, And then it will display them.
My firebase Database
So for example when I click on the button of the first column I will get the files that are stored in the folder with name 2 form firebase.database. The result of after I click the first button will be this:
My source code works fines as it gets the files from the corresponding folders from firebase.database. The problem that i have is when i dont refresh the page and i click a button again then the outpout will be the result of the previous button click plus the new one. For example if i dont refresh my page and i click the second button to get the files from the file from database with the name = 3 the outpout will be :
The outpout is a merging of all the results that i have oupouted so far. If i refresh my page and click on the second button now i will get the result i want which it is:
How can i edit my source code so the tables wont merge?
My source code is the follwing:
Source code of saving the value after button is clicked and passsing it to function:
var contactName; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contact"]').click(function() {
contactName = $(this).val(); //set var contactName to value of the pressed button
store(contactName);
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
Source code of function receiving the value and displays the corresponding file from firebase database:
function store(value){
var tblUsers = document.getElementById('tbl_users_list');
var databaseRef = firebase.database().ref().child(`files/${value}/`);
var rowIndex = 1;
databaseRef.once('value',function(snapshot){
snapshot.forEach(function(childsnapshot) {
var childKey = childsnapshot.key;
var childData = childsnapshot.val();
//var urls = childData.url;
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var button = row.insertCell(2);
var itd = document.createElement('input');
itd.setAttribute("type","button");
itd.setAttribute("value","View");
itd.onclick=function () {
window.open(childData.url);
};
cellId.appendChild(document.createTextNode(childData.filename));
cellName.appendChild(document.createTextNode(childData.created));
button.appendChild(itd);
rowIndex = rowIndex+1;
//document.write(username);
})
});
}
Thanks in Regards
You only append data to the existing table, without ever removing existing rows in the table:
var row = tblUsers.insertRow(rowIndex);
You should make sure to remove all existing rows before adding the new one(s):
for (var i = tblUsers.rows.length; i >= 0; i--) {
tblUsers.deleteRow(i - 1);
}

acts_as_votable javascript html table

I'm trying to use the acts_as_votable gem in ruby on rails. However, I get stuck when I need to add the button to the view.
I want to add a voting system to a list of item which are put into an html table as users fill out the form in the web browser.
I can insert a 'like' button in each row for each 'destination' item. However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?
Here is the dashboard.js:
var insertDest = function(dest) {
// Find a <table> element with id="myTable":
var table = document.getElementById("destTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var name_cell = row.insertCell(0);
var address_cell = row.insertCell(1);
// var delete_cell = row.insertCell(2);
var like_cell = row.insertCell(2);
like_cell.innerHTML = '<input class="Like" type="button" value="Like" />';
var like_count_cell = row.insertCell(3);
like_count_cell.innerHTML= 0;
// Add some text to the new cells:
name_cell.innerHTML = dest.name;
address_cell.innerHTML = dest.address;
// delete_cell.innerHTML = "<div class='del'>x</div>";
addMarker(dest.address,map);
};
var insertAllDest = function(trip){
var d = trip.destinations;
for (i in d){
insertDest(d[i]);
}
};
However, does this mean I need to write a 'attachLikeHandler' function
to deal with what happens when the like button is clicked?
Yes:
$(".like").on('click', function() {
$.ajax({
method: "PUT",
url: "/photos/" + $(this).attr("id"),
success: function(msg_from_server) {
alert(msg_from_server); //"Thanks for voting!" or "Sorry, you already voted!"
}
});
});
If you have a route declared as resources :photos, then a url like /photos/12 will send a request to photos#update, then inside the update action params[:id] will be 12. Note that you'll need to add the resource id to the html when constructing the html.

Generate input button with onClick function using JavaScript DOM

I use JavaScript to generate form input fields on my page. Everything works fine, except the button. I came across some problems generation the button's onClick function using DOM. You can see the code below, but on my page, there is no the onClick function as the attribute of the input button tag:
n = 1;
function generate() {
var radiomore = document.createElement("input");
radiomore.type = "button";
radiomore.name = "opt[" + n + "]";
radiomore.value = "Add more options";
radiomore.setAttribute = ('onClick',addradiomore);
var div = document.createElement("div");
div.innerHTML = "Op: " + radiomore.outerHTML + "<br/>";
document.getElementById("mydiv").appendChild(div);
n++;
}
function addradiomore() {
//here goes the function code
}
And this is what it generates on my page:
<input type="button" name="opt[1]" value="Add more options">
There is no function?!?!
P.S.
Even if I use like this it doesn't work:
radiomore.onclick = addradiomore();
You should use this:
radiomore.onclick = addradiomore;
DEMO
What about:
radiomore.onclick = function () {
addradiomore();
};

Categories