Why my ajax function cannot append html at targeted div element? - javascript

I am submitting a html form through AJAX and then appending results at particular div element.The corresponding ajax is :-
$(document).ready(function(){
$('.commentbutton').click(function(){
var idb=$(this).attr('id');
var formid=$('#Comment'+idb);
datab=getFormData(formid);
$.ajax({
type:"POST",
url:'/submit/channelcomment',
data:datab,
success:function(data){
console.log(data.content);
console.log(data.profile);
var html="<div class='CommentRow'><a href='/Channel/"+data.profile+"/'style='font-weight: bolder;margin-right: 10px;display: inline-block;'>"+data.profile+"</a>"+data.content+"</div>"
console.log('Done');
idt=$('#CommentBody'+idb);
console.log(idt);
idt.append(html);
},
}),
event.preventDefault();
});
});
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
The desired position at which i'm trying to append html is as follows:-
<div class="CommentBody" id="CommentBody{{c.id}}">
</div>
Here c.id and idb equals to 1.But it is not appending html.

When you say
But it is not appending html.
What is actual behavior?
I tried the dummy code as below and it is working fine.
$(document).ready(function() {
$('.commentbutton').click(function() {
var html = "<div class='CommentRow'><a href='/Channel/data.profile/'style='font-weight: bolder;margin-right: 10px;display: inline-block;'>data.profile</a>data.content</div>"
var idb = '1';
idt = $('#CommentBody' + idb);
alert(idt);
idt.append(html);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='commentbutton'>Comment</button>
<div class="CommentBody" id="CommentBody1">
</div>

Related

How do I get an element with a specific ID from getElementsByClassName?

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/

Accessing <div> elements by name in jQuery

I have the following content in -
var jsonObj = [ {"name" : "Jason"},{"name":"Bourne"},{"name":"Peter"},{"name":"Marks"}];
<!---->
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
function getNames(jsonObj){
var response = JSON.stringify(jsonObj);
for ( var i = 0, len = jsonObj.length; i < len; i++) {
var nameVal = jsonObj[i].name;
response = response.replace(nameVal,replaceTxt(nameVal,i));
}
return response;
}
function replaceTxt(nameVal,cnt){
return "<u id='"+cnt+"' name='names' >"+nameVal+"</u> ";
}
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
and html as below -
<button id="getname">Get Name</button>
<div id="nameData"></div>
Double clicking on names value doesn't generating alerts.
are you sure it is..
<dev id="nameData"></dev>
OR
<div id="nameData"></div>
this works...but you have an extra }); in the question...(don't know if it is a typo)
fiddle here
Try this:
$(document).ready(function(){
$('u[name="names"]').live("dblclick", function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
Try moving this code:
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
inside
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
});
like:
$("#getname").click(function() {
var response = getNames(jsonObj);
$("#nameData").html(response);
$('u[name="names"]').dblclick(function(){
var currentId = $(this).attr('id');
alert(currentId);
});
});
});
You don't need the last "});" Or you didn't paste the whole code.
Look here: http://jsfiddle.net/4cajw/1/
As your code suggest that you are .dblclick()ing on dynamically generated element, that don't work, you have to select parent elem which exist in the document
$(document).on('dblclick','u[name="names"]', function(){
var currentId = $(this).attr('id');
alert(currentId);
});
try this out.
JSON.stringify - object -> JSON.
JSON.parse - JSON -> object

Javascript results to div

Q1: My point is create many buttons as many rows of array. Like this, only one button appears.
<script type="text/javascript">
var myArray = [];
$('#button').click(function(){
var value1 = $('#value1').val();
var value2 = $('#value1').val();
var value3 = $('#value1').val();
var newArray = [];
var newArray[0] = value1;
var newArray[1] = value2;
var newArray[2] = value3;
myArray.push(newArray);
$("#save").append(
$("<button>").click(function() {
myFunction.apply(null, myArray);
}).text("Click me!")
);
});
});
function myFunction(value1,value2,value3)
{
var jsonData = $.ajax({
url: "file.php?value1=" + value1 + "&value2=" + value2 + "&value3=" + value3
dataType: "json",
async: false
}).responseText;
(...)
}
//edited: problem maybe found. I said buttons dont do anything because of this.
OUTPUT: file.php?value1=paul,23,USA&value2=undefined&value3=undefined
//it seems that value1 gets all values :s
</script>
<div id ="save"></div>
Im looking for a solution that return someting like this:
eg:
<!--<button onclick="myFunction(name,age,country)">Click me</button>-->
<button onclick="myFunction(paul,23,USA)">Click me</button>
<button onclick="myFunction(john,23,USA)">Click me</button>
EDITED MY CODE WITH MORE DETAILS
.html replaces, and your quotes are mismatched. But it doesn't matter - jQuery is better at manipulating the DOM than it is at manipulating strings. Try:
$("#save").append(
$.map(myArray, function(item) {
return $("<button>").click(function() {
myFunction.apply(null, item);
}).text("Click me");
})
);
Here's a demo.
You're only seeing one button because the .html() method replaces the html of the element. It doesn't append.
Luckily, jQuery has a method for the behavior you want, fittingly called append. Change it to look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>");
$("#save").append(button) ;
}
I intentionally left the onclick behavior out of that snippet. You can write it in the html of the button you create, as you have been, or you can do it with jQuery - the second method is preferable, and would look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>")
.click(function(){
// call the actual function you want called here
});
$("#save").append(button);
}
Did you mean this:
<div id="save">
</div>
<script type="text/javascript">
function addButtons(){
for(i=0;i<myArray.length;i++)
{
var button = $('<button id="btn_'+i+'" onclick="myFunction(this);">Click me</button>')
$(button).data('details',myArray[i]).appendTo("#save");
}
}
function myFunction(element){
alert($(element).data('details'));
}
</script>
This is because you are replacing the html in the $("#save") in the loop . Try
$("#save").append("<button onclick="myFunction('"+myArray[i]+"')">Click me</button>") ;
for(i=0;i<myArray.length;i++){
//Create a new DOM button element ( as jQuery object )
// Set the current button index, and add the click action
var button = $('<button />').data('myindex', i).click(function(){
var myArrayItem = myArray[$(this).data('myindex')];
alert(myArrayItem);
}).html('My label n. '+i);
$('#save').append(button)
}
Why bothering with all the JQuery and complicated code, just use simple way to implement this
<script type="text/javascript" >
var myArray = ["New York", "Boston", "San Jose", "Los Angeles"];
var strHTML = "";
for(i=0;i<myArray.length;i++)
{
strHTML += "<button onclick='myFunction("+i+")'>Click me</button>";
}
$("#save").innerHTML = strHTML;
function myFunction(index)
{
alert(index);
// do your logic here with index
}
</script>

How to create a custom JSON based on form values?

I am creating a JSON based on a dynamic form values below, when the user submits, i am displaying the json feed in #results
Is it also possible to get all the values in the form when generating the JSON, I want to get the
name, ids,
title information,
input value etc
and then create/display the JSON in the order below?
A working version can viewed here :
http://jsfiddle.net/dev1212/GP2Y6/25/
Currently its not retuning any values and getting some undefined..
the code peice i tried is below
<script>
x = function(selector){
var attrs = [];
$(selector + " input").each(function(){
var attrObject = {};
$(this.attributes).each(function(index, attr){
attrObject[attr.name] = attr.value;
attrObject[attr.va] = attr.value;
//console.log(attrObject)
});
attrs.push(attrObject);
attrObject = {};
});
return attrs;
}
$(document).ready(function(){
alert(JSON.stringify(x("#myform")));
});
</script>
<script type="text/javascript" src="/www/include/js/jquery.min.js"></script>
<script>
x = function(selector){
var attrs = [];
$(selector + " input").each(function(){
var attrObject = {};
$(this.attributes).each(function(index, attr){
attrObject[attr.name] = attr.value;
//console.log(attrObject)
});
attrs.push(attrObject);
attrObject = {};
});
return attrs;
}
$(document).ready(function(){
alert(JSON.stringify(x("#myForm")));
});
</script>
<form id="myform" class="form-wd">
<input class="ui-dform-text" type="text" title="data for network.node1.eth0.ipaddr" name="network.node1.eth0.ipaddr">
</form>

is there any way findout duplicate id name in the page using jquery

my script is :
$('document').ready(function () {
var position = 0;
var data = [{'id':'user1'},{'id':'user2'},{'id':'user3'},{'id':'user4'},{'id':'user5'}];
$('#add').click(function() {
var newdiv=$('<div></div>').attr('id', data[position].id).text(data[position].id);
$("#container").append(newdiv);
position++;position %= data.length;
});
});
My html is:
<html>
<body>
<button id="add">Add new div</button>
<div id="container"><div id="user3"></div></div>
</body>
</html>
when click a button i am appending new divs with some id name here before insert div i want to check all div id names if anything matches i don't want to append that div
my jsfiddle is here
$("#add").click(function() {
...
$.each(data, function(index, value) {
$("<div />").attr('id', value.id).text(value.id).appendTo("#container");
});
});
Please read the jQuery Cookbook. It'll help with the... headaches.
use array.length as the new id?
$('document').ready(function () { var data = [{'id':'user1'},{'id':'user2'},{'id':'user3'},{'id':'user4'},{'id':'user5'}];
$('#add').click(function() {
var newdiv=$('<div></div>').attr('id', data.length).text(data.length); $("#container").append(newdiv);
var newData = {};
newData.id = 'user'+data.length;
data[data.length] = newData});
});
Thanks thiefmaster ;)

Categories

Resources