Get text value from a button s created dynamically jquery - javascript

So i am dynamically adding buttons to a table based on array values returned from my generateFolderTree function, problem is i can't seem to get the text value of a clicked button or even get any events when i click the created buttons. How can i get the name of a clicked button? Code below....Thanks
Jquery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
$("#selectFolder").click(runMyFunction);
});
function runMyFunction(){
google.script.run
.withSuccessHandler(successCallback)
.withFailureHandler(showError)
.generateFolderTree();
$("#hiddenAttrib").hide();
}
function showError(error) {
console.log(error);
window.alert('An error has occurred, please try again.');
}
function successCallback(returnedArray)
{
console.log("returnedArray" + returnedArray);
var folders = returnedArray;
console.log("folders" + folders);
var i = 0;
//row;
for( i=0; i<folders.length;i++)
{
console.log("i = " + i);
var row = $('<p><tr><button class = "selectedFolder">' + folders[i] + '</button></tr></p>');
$("#source").append(row.html());
}
}
$(".selectedFolder").click(function () {
var text = $(this).text();
console.log(text);
$("#dialog-status").val(text);
});
</script>
Show.html
<!-- USe a templated HTML printing scriphlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile("Stylesheet").getContent(); ?>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<div>
<div class = "block" id = "dialog-elements">
<button class = "selectFolder" id = "selectFolder" >Select a Folder</button>
</div>
<!-- This block is going to be hidden until the user selects a folder -->
<div class = "block" id = "hiddenAttrib">
<p><label for = "SelectedFolder"> Selected Folder: </label></p>
<p><label id = "foldername"> Folder Name: </label></p>
<p><label id = "folderid"> Folder ID: </label></p>
</div>
<div class = "folderTable" id = "folderTable">
<p><label class = "showStatus" id = "dialog-status">Selected Folder: </label></p>
<table style = "width:100%" id = "source">
</table>
</div>
</div>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('ShowJavaScript').getContent(); ?>

$('document').on('click', '.selectedFolder', function () {
alert($(this).text())
});

Put this piece of code of yours in $(document).ready
$(".selectedFolder").click(function () {
var text = $(this).text();
console.log(text);
$("#dialog-status").val(text);
});

use
$(ELEMENT/CLASS/ID).on('click', function(){});
instead of
$(ELEMENT/CLASS/ID).click
click() function doesnt consider elements added to DOM dynamically before we used to use live() for attaching events for dynamically created element but since live() is depreciated we should use on()
on() acts as live()

Related

How to make the materializecss dropdown work when added dynamically

Following is an example of a sample webform I made in Google Apps Script, where I'm trying to dynamically add three select dropdowns and an input element whenever the add button is clicked. The elements should render in following order -
dropdown dropdown input dropdown.
I'm using materialize framework for this.
After a lot of trying and going through the materializecss documentation, I was able to render the text input field as expected. But, the dropdowns still won't render. Clearly, I'm making some mistake, cannot figure out what and where.
I'm including the code files-
Code.gs
function doGet(e) {
Logger.log(e);
return HtmlService.createTemplateFromFile('form_materialize').evaluate();
}
function include(fileName){
return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}
form_materialize.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!-- google font pack link -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Mini materialize.css cdn link -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include('css_scripts'); ?>
</head>
<body>
<div class="container">
<div class = "row">
<h1>A Sample Form</h1>
</div>
<div id="productsection">
<!-- product details like "Product Type"(dropdown), "Products"(dropdown), "Product Qty"(text input field), "Unit"(dropdown) to be added here dynamically -->
</div>
<div class = "row">
<a class="btn-floating btn-large waves-effect waves-light red" id="addproduct"><i class="material-icons">add</i></a>
</div>
</div>
<!-- Mini materialize.js cdn link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include('js_scripts_materialize'); ?>
</body>
</html>
js_scripts_materialize.html
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, options);
});
let counter = 0;
const orderTypeList = ["PH", "ECOM"];
const optionList = ["Test Product 1", "Test Product 2", "Test Product 3", "Test Product 4", "Test Product 5"];
const unitOptionList = ["KGS", "PCS", "BAGS"];
document.getElementById("addproduct").addEventListener("click", addInputField);
function addInputField(){
counter++;
// everytime when "add product" button is clicked, the following elements must be added to the "<div id="produc></div>" tag.
// <div class="row">
// <div class="input-field col s4" id="divone">
// <select id="productX">
// <option>option-i</option>
// <option>option-1</option>
// <option>option-2</option>
// ...
// ...
// <option>option-n</option>
// <select>
// </select>
// <div class="input-field col s4" id="divtwo">
// <input id="productqtyX" type="text">
// <label for="productqtyX">Quantity</label>
// </div>
// <div class="input-field col s4" id="divthree">
// <select id="productUnitX">
// <option>option-1</option>
// <option>option-2</option>
// ...
// ...
// <option>option-n</option>
// </select>
// </div>
// </div>
// creates a new div of class row
const newDivElem = createElementTemplate('div', null, ['row']);
// creates a new select tag for order type dropdown
const newOrderTypeSelectElem = createElementTemplate('select', "ordertype" + counter.toString());
// generates the content of the dropdown for products and is inserted to the above "productX" select tag
createOptionsElem(newOrderTypeSelectElem, orderTypeList);
// creates a new select tag for product dropdown
const newProductSelectElem = createElementTemplate('select', "product" + counter.toString());
// generates the content of the dropdown for products and is inserted to the above "productX" select tag
createOptionsElem(newProductSelectElem, optionList);
// creates a input element for quantity input
const newQtyInputElem = createElementTemplate('input', 'productqty' + counter.toString(), ['validate']);
newQtyInputElem.type = 'text';
// creates a label for the quantity input element
const newQtyLabelElem = createElementTemplate('label');
newQtyLabelElem.textContent = "Quantity";
//Creates a new select element for product quantity unit(dropdown)
const newUnitSelectElem = createElementTemplate('select', 'productqtyunit' + counter.toString());
// generates the content of the dropdown for units and is inserted to the above "productqtyunitX" select tag
createOptionsElem(newUnitSelectElem, unitOptionList);
//create inner "div" tags with class "input-field col s4" as described in materializecss documentation
const innerDivElems = [];
for(let i = 0; i < 4; i++){
innerDivElems.push(createElementTemplate('div', `div${(Number(i) + 1)}`, ['input-field', 'col', 's3']));
}
innerDivElems[0].appendChild(newOrderTypeSelectElem);
innerDivElems[1].appendChild(newProductSelectElem);
innerDivElems[2].appendChild(newQtyInputElem);
innerDivElems[2].appendChild(newQtyLabelElem);
innerDivElems[3].appendChild(newUnitSelectElem);
//Inserts select, quantityInput, quanityLabel, newUnitSelectTag tags in div child
for(let i in innerDivElems){
newDivElem.appendChild(innerDivElems[i]);
}
// Finally, appends the newly created div tag to the productSection tag.
document.getElementById('productsection').appendChild(newDivElem);
}
function createOptionsElem(selectElem, optionsArr){
const newDefaultOptionElem = document.createElement('option');
newDefaultOptionElem.disabled = true;
newDefaultOptionElem.setAttribute('selected', true);
newDefaultOptionElem.textContent="Choose your option";
selectElem.appendChild(newDefaultOptionElem);
for(let i in optionsArr){
const newOptionElem = document.createElement('option');
newOptionElem.textContent = optionsArr[i];
newOptionElem.value = optionsArr[i];
// Inserts the option tag in select tag
selectElem.appendChild(newOptionElem);
}
}
// function to create a new element
function createElementTemplate(tagType, idVal, classNameList){
const newElement = document.createElement(tagType);
if(idVal !== undefined)
newElement.id = idVal;
if(classNameList !== undefined){
for(let i in classNameList){
newElement.classList.add(classNameList[i]);
}
}
return newElement;
}
</script>
Although I'm not sure whether I could correctly understand your expected result, how about the following modification?
In this modification, your js_scripts_materialize.html is modified.
Modified script:
I think that in this case, this part might not be required to be used.
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, options);
});
And also, please modify addInputField() as follows.
From:
document.getElementById('productsection').appendChild(newDivElem);
To:
document.getElementById('productsection').appendChild(newDivElem);
var elems = document.querySelectorAll('select'); // Added
M.FormSelect.init(elems); // Added
By this modification, I thought that when you click a red button, you can see the dropdown lists.

How do I get cell values on click event from webpage tabs after the first one?

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.

Adding onclick event on dynamic checkbox

I'm trying to make a 'CRUD' in pure Javascript, it's almost done, the only thing that I need is preparing the inputs with the value of <li>, to do it, I'd like to add an onclick event in a checkbox that is created dynamically in the function insert(), but everytime I click the checkbox nothing happens.
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
btnInsert = document.getElementById("btnInsert");
btnEdit = document.getElementById("btnEdit");
btnDelete = document.getElementById("btnDelete");
vname = document.getElementById("tbName");
ul = document.getElementsByTagName("ul")[0];
btnInsert.onclick = insert;
btnDelete.onclick = remove;
}
function insert(){
li = document.createElement("li");
li.innerHTML = vname.value;
li.innerHTML += " <input type='checkbox' onclick='select()' value='Select' /> Update";
ul.appendChild(li);
vname.value = "";
}
function select(){
alert("Checked");
}
function remove(){
var lis = document.getElementsByTagName("li");
for(i = 0; i<lis.length; i++){
lis[i].onclick = function(){
this.remove();
}
}
}
</script>
</head>
<body>
<label for="tbName">Name: </label>
<input name="tbName" id="tbName"/><br /><br />
<button id="btnInsert">Insert</button>
<button id="btnEdit">Edit</button>
<button id="btnDelete">Delete</button>
<br /><br />
<ul>
</ul>
</body>
</html>
It seems the name select is causing conflict since I could get your code working with the following changes:
HTML
li.innerHTML += " <input type='checkbox' onclick='sel()' value='Select' />Update";
Javascript
function sel(){
alert("Checked");
}
Further tests show that if we log the contents of the function with:
li.innerHTML += " <input type='checkbox' onclick='console.log(select.toString)' value='Select' />Update";
the console shows the following
function select() { [native code] }
So my guess is that select is the name of a function already defined by the browser, hence why you can't use it as a name for your functions.
In short, your code triggers another select function, not the one you defined in your source code.
The OP doesn't want it to fire on the LI, he wants it to fire on the checkbox!
Give your dynamic checkbox an ID value like chkBox1.
Now after you have appended it to the document, you can call it with:
var thechkBox=document.getElementById("chkBox1");
Now you can hit thechkBox with:
thechkBox.addEventListener("click", itfired); //itfired is the script that captures the click event.
That is one of many Events you would then have access to (https://www.w3schools.com/js/js_htmldom_events.asp)!
If you needed the dynamic checkbox to perform a function "on"click!

How to add working dropify inputs dynamically

I have form which gets clone when user click on add more button .
This is how my html looks:
<div class="col-xs-12 duplicateable-content">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
<i class="ti-close"></i>
</button>
<input type="file" id="drop" class="dropify" data-default-file="https://cdn.example.com/front2/assets/img/logo-default.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
...
</div>
This my jquery part :
$(function(){
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone(true, true)).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Now I want every time user clicks on add more button the id and class of the input type file should be changed into an unique, some may be thinking why I'm doing this, it I because dropify plugin doesn't work after being cloned, but when I gave it unique id and class it started working, here is what I've tried :
function randomString(len, an){
an = an&&an.toLowerCase();
var str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
var r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
} var ptr = randomString(10, "a");
var className = $('#drop').attr('class');
var cd = $("#drop").removeClass(className).addClass(ptr);
Now after this here is how I initiate the plugin $('.' + ptr).dropify().
But because id is still same I'm not able to produce clone more than one.
How can I change the id and class everytime user click on it? is there a better way?
Working Fiddle.
Problem :
You're cloning a div that contain already initialized dropify input and that what create the conflict when you're trying to clone it and reinitilize it after clone for the second time.
Solution: Create a model div for the dropify div you want to clone without adding dropify class to prevent $('.dropify').dropify() from initialize the input then add class dropify during the clone.
Model div code :
<div class='hidden'>
<div class="col-xs-12 duplicateable-content model">
<div class="item-block">
<button class="btn btn-danger btn-float btn-remove">
X
</button>
<input type="file" data-default-file="http://www.misterbilingue.com/assets/uploads/fileserver/Company%20Register/game_logo_default_fix.png" name="sch_logo">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
</div>
JS code :
$('.dropify').dropify();
$("body").on("click",".btn-duplicator", clone_model);
$("body").on("click",".btn-remove", remove);
//Functions
function clone_model() {
var b = $(this).parent(".duplicateable-content"),
c = $(".model").clone(true, true);
c.removeClass('model');
c.find('input').addClass('dropify');
$(b).before(c);
$('.dropify').dropify();
}
function remove() {
$(this).closest('.duplicateable-content').remove();
}
Hope this helps.
Try this:
$(function() {
$(document).on("click", ".btn-duplicator", function(a) {
a.preventDefault();
var b = $(this).parent(".duplicateable-content"),
c = b.clone(true, true);
c.find(".dropify").removeClass('dropify').addClass('cropify')
.attr('id', b.find('[type="file"]')[0].id + $(".btn-duplicator").index(this)) //<here
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content")
})
});
Fiddle
This does what you specified with an example different from yours:
<div id="template"><span>...</span></div>
<script>
function appendrow () {
html = $('#template').html();
var $last = $('.copy').last();
var lastId;
if($last.length > 0) {
lastId = parseInt($('.copy').last().prop('id').substr(3));
} else {
lastId = -1;
}
$copy = $(html);
$copy.prop('id', 'row' + (lastId + 1));
$copy.addClass('copy');
if(lastId < 0)
$copy.insertAfter('#template');
else
$copy.insertAfter("#row" + lastId);
}
appendrow();
appendrow();
appendrow();
</script>
Try adding one class to all dropify inputs (e.g. 'dropify'). Then you can set each elements ID to a genereted value using this:
inputToAdd.attr('id', 'dropify-input-' + $('.dropify').length );
Each time you add another button, $('.dropify').length will increase by 1 so you and up having a unique ID for every button.

How to add array items to <li> Jquery

I'm working on something really simple, a short quiz, and I am trying to make the items I have listed in a 2-d array each display as a <li>. I tried using the JS array.join() method but it didn't really do what I wanted. I'd like to place them into a list, and then add a radio button for each one.
I have taken the tiny little leap to Jquery, so alot of this is my unfamiliarity with the "syntax". I skimmed over something on their API, $.each...? I'm sure this works like the for statement, I just can't get it to work without crashing everything I've got.
Here's the HTML pretty interesting stuff.
<div id="main_">
<div class="facts_div">
<ul>
</ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me">
</form>
</div>
And, here is some extremely complex code. Hold on to your hats...
$(document).ready (function () {
var array = [["Fee","Fi","Fo"],
["La","Dee","Da"]];
var q = ["<li>Fee-ing?","La-ing?</li>"];
var counter = 0;
$('.myBtn').on('click', function () {
$('#main_ .facts_div').text(q[counter]);
$('.facts_div ul').append('<input type= "radio">'
+ array[counter]);
counter++;
if (counter > q.length) {
$('#main_ .facts_div').text('You are done with the quiz.');
$('.myBtn').hide();
}
});
});
Try
<div id="main_">
<div class="facts_div"> <span class="question"></span>
<ul></ul>
</div>
<form>
<input id="x" type="button" class="myBtn" value="Press Me" />
</form>
</div>
and
jQuery(function ($) {
//
var array = [
["Fee", "Fi", "Fo"],
["La", "Dee", "Da"]
];
var q = ["Fee-ing?", "La-ing?"];
var counter = 0;
//cache all the possible values since they are requested multiple times
var $facts = $('#main_ .facts_div'),
$question = $facts.find('.question'),
$ul = $facts.find('ul'),
$btn = $('.myBtn');
$btn.on('click', function () {
//display the question details only of it is available
if (counter < q.length) {
$question.text(q[counter]);
//create a single string containing all the anwers for the given question - look at the documentation for jQuery.map for details
var ansstring = $.map(array[counter], function (value) {
return '<li><input type="radio" name="ans"/>' + value + '</li>'
}).join('');
$ul.html(ansstring);
counter++;
} else {
$facts.text('You are done with the quiz.');
$(this).hide();
}
});
//
});
Demo: Fiddle
You can use $.each to iterate over array[counter] and create li elements for your options:
var list = $('.facts_div ul');
$.each(array[counter], function() {
$('<li></li>').html('<input type="radio" /> ' + this).appendTo(list);
}
The first parameter is your array and the second one is an anonymous function to do your action, in which this will hold the current element value.
Also, if you do this:
$('#main_ .facts_div').text(q[counter]);
You will be replacing the contents of your element with q[counter], losing your ul tag inside it. In this case, you could use the prepend method instead of text to add this text to the start of your tag, or create a new element just for holding this piece of text.

Categories

Resources