Javascript results to div - javascript

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>

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/

Format number with commas in .each function

So I have some js which is converting a div class's number through a daily exchange rate engine. It outputs correctly as it should and I am now trying to separate this number it outputs using jQuery and a function I found whilst doing some research. I am trying to feed the number to the function using a .innerHTML method. I have got the function to alert a converted number but I have multiple elements which this function should run for, so have used an .each function - this is where something isn't working. I get no alert so I think there is something wrong with the .each code.
Can anyone see anything that might be causing it?
The complete code is here:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
//alert("Product Costs" + rate.toFixed(4))
}
$.getJSON("http://api.fixer.io/latest", demo);
});
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
</script>
I think the reason is
$("#converted").each(function() {
var convertedPrice = $(this.innerHTML);
function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
setTimeout (runThis, 100);
});
happends before you created the converted elements. Because you put the creation inside a get call.
I suggest you put this inside the callback of your get call.
Something like this
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
//alert("Product Costs" + rate.toFixed(4))
});
$(".converted").each(function() {
var convertedPrice = $(this).html();
console.log(ReplaceNumberWithCommas(convertedPrice));
});
}
$.getJSON("https://api.fixer.io/latest", demo);

Date entries in the array are not printed

I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.
On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});
Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;
You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.

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

check if the div id in JavaScript

I have project that concerns about calendars, at first i have 1 calendar and now i want to have another one but they have different values.
<div id="cal">
....
</div>
<div id="calq">
....
</div>
my question is, how can I check if div id is "calq" in javascript?
if div.id == "calq" ?
...
at first i have ...
<script type="text/javascript">
monthYear = Date.today();
var cal = new Calendar();
cal.generateHTML();
$('#cal').html(cal.getHTML());
setMonthPrice();
setSpecialPrice()
</script>
then i added
<script type="text/javascript">
monthYear = Date.today();
var calq = new Calendar();
calq.generateHTML();
$('#calq').html(calq.getHTML());
setMonthQuantity();
setSpecialQuantity();
</script>
but the setMonthQuantity() also called by cal, i just want the setMonthQuantity() only for calq
function setMonthQuantity()
{
var weekdayBaseQuantity;
weekdayBaseQuantity = {{ product.quantity }};
$('td.calendar-day').append('<div class="dayquantity">' + weekdayBaseQuantity + '</div>');
$('td.Sat .dayquantity, td.Sun .dayquantity').text( weekdayBaseQuantity );
}
To determine the existence, in clean javascript
if(document.getElementById("calq")!='undefined')
{
// do something, it exists
}
using jquery
if($("#calq").length)
{
// do something, it exists
}
To check the id, in clean javascript
if(this.getAttribute('id')=="calc")
{
// do something, it exists
}
Using jquery
if($(this).attr("id")=="calq")
{
// do something, it exists
}
You can do check it, for example, via Jquery. I suppose that you want to make something like switch and for each div do some operation. If I'm right you can use Jquery's each function for looping against div elements and following condition for checking id's.
if($(this).attr("id")=="calq")
Here you go:
if (​$('#calq').length === 1) {
// there is id = calq
}​​​
Seems like the best solution would be to pass in the div to the functions you are calling. That way you know the div you are dealing with.
eg.
<script type="text/javascript">
monthYear = Date.today();
var cal = new Calendar();
cal.generateHTML();
var calDiv = $('#cal');
calDiv.html(cal.getHTML());
setMonthPrice(calDiv);
setSpecialPrice(calDiv)
</script>
<script type="text/javascript">
monthYear = Date.today();
var calq = new Calendar();
var calqDiv = $('#cal');
calqDiv.html(cal.getHTML());
setMonthQuantity(calqDiv);
setSpecialQuantity(calqDiv);
</script>
I am assuming the $('td.calendar-day') is in the calendar HTML? If so setMonthQuantity would be something like
function setMonthQuantity(calDiv)
{
var weekdayBaseQuantity;
weekdayBaseQuantity = {{ product.quantity }};
calDiv.closest('td.calendar-day').append('<div class="dayquantity">' + weekdayBaseQuantity + '</div>');
calDiv.closest('td.Sat .dayquantity, td.Sun .dayquantity').text( weekdayBaseQuantity );
}

Categories

Resources