Get the ID of a dynamic text field via dynamically created button - javascript

See below code. I'm creating two text fields dynamically. In one of those text fields 2 buttons are also created. When either of these buttons are clicked how could I get the ID of the text field that doesn't have buttons?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/><button type="button" runclass0">Run</button><button type="button" class="removeclass0">Next</button>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});

Do you mean something like this?
I know I didn't make use of your data attributes. However, there are million ways to re-include them, I simply thought it was best to show you an easier way without relying on multiple similar ID's, found by using data. That way just seemed like more work and headache, to me anyway.
jsFiddle: live example
$(function() {
function createFields(e) {
var inWrap = $('<div />', { class: 'name-wrapper' }),
nameWrap = $('<div />', { class: 'name' }).appendTo(inWrap),
outWrap = $('<div />');
nameWrap.append(
$('<input />', { class: 'fTypex', placeholder: 'Thought of the day...', type: 'textarea' }),
$('<button />', { text: 'Run', type: 'button' }),
$('<button />', { text: 'Next', type: 'button' })
);
outWrap.append(
$('<input />', { type: 'textarea' })
);
$('#InputsWrapper').append(inWrap);
$('#OuterWrapper').append(outWrap);
}
$(document)
.on('click', '#tfButton', createFields)
.on('click', '#InputsWrapper button', function(e) {
var i = $(this).closest('.name-wrapper').index(),
inp = $('#OuterWrapper input')[i],
$inp = $(inp);
console.log(i, inp, $inp);
// could use like
$('.highlight').removeClass('highlight');
$inp.addClass('highlight');
})
})
And if you insist on your data attributes and that weird runclass0 attr and the other class, here's an alternate fiddle including those little items. You'll notice very little change in structure tho.
Alt jsFiddle
$(function() {
function createFields(e) {
var inWrap = $('<div />', { class: 'name-wrapper' }),
nameWrap = $('<div />', { class: 'name' }).appendTo(inWrap),
outWrap = $('<div />'),
iCnt = $('#InputsWrapper .name-wrapper').length + 1;
nameWrap.append(
$('<input />', { class: 'fTypex', 'data-tfcount': iCnt, id: 'field_'+iCnt, placeholder: 'Thought of the day...', type: 'textarea' }),
'<button runclass0 type="button">Run',
$('<button />', { class: 'removeclass0', text: 'Next', type: 'button' })
);
outWrap.append(
$('<input />', { 'data-tfcount': iCnt, id: 'tf_'+iCnt, type: 'textarea' })
);
$('#InputsWrapper').append(inWrap);
$('#OuterWrapper').append(outWrap);
}
$(document)
.on('click', '#tfButton', createFields)
.on('click', '#InputsWrapper button', function(e) {
var i = $(this).closest('.name-wrapper').index(),
inp = $('#OuterWrapper input')[i],
$inp = $(inp);
// see console for more info: F12 in most of today's browsers
if (console['log']) console.log(i, inp, $inp);
// could use like
$('.highlight').removeClass('highlight');
$inp.addClass('highlight');
})
})

Related

Button after div that contains dynamic elements without touch HTML

i need an help.
I have this code and i have to put a Save button to the end for store the changes or the new entry in DB.
I have the problem that i haven't idea to how put button in the end without change HTML code because i can't, i wuold insert button via javascript,
how can i do?
p.s: The problem is that i can't insert in those function because the function under here is called everytime a press a button, if a press another time is called another, and again.
p.s2: Tell me if the code is ok, in other case tell me how can i improve this
Thank you
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
$("#btnSave").remove();
div.append("<input type='button' value='Save' id='btnSave' />");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
I removed the button and placed it when needed. Hope it helps. Cheers..!!

How to generate a unique id?

I am running twice the call to google in order to get 20 images (google by default only gives you a set of 10 images for a single call).
However, I need to generate a single unique id for each element i get. Here it is the jQuery I am using but the second set of 10 images gets the same id as per the previous set:
function loadImage() {
var uniqueId = (function() {
var counter = 0;
return function(prefix) {
counter++;
return prefix ? prefix + '' + counter : counter;
}
})();
// GOOGLE IMAGES FRONT
function createGoogleImagesLoad(initialValue) {
var termS;
termS = $("#usp-title").val();
var _start = initialValue || 1;
var imagesCount = 10;
var myCx = 'MY_CX';
var myKey = 'MY_KEY';
var $grid = $('.grid').packery({
itemSelector: '.grid-item',
percentPosition: true
});
return function() {
$.getJSON("https://www.googleapis.com/customsearch/v1", {
q: termS,
alt: "json",
searchType: "image",
cx: myCx,
num: imagesCount,
start: _start,
key: myKey,
language: "it",
rights: "cc_publicdomain, cc_attribute",
filter: "1",
safe: "high",
imgType: "photo",
fileType: "jpg"
},
function (data) {
$.each(data.items, function(i, item) {
var uniq = uniqueId('thing_');
var $items = $('<div class="col-xs-12 col-md-6 grid-item">'.concat(
'<div class="thumbnail">',
'<input type="checkbox" name="', uniq, '" value="valuable" id="', uniq, '" />',
'<label for="', uniq, '">',
'<img class="img-responsive" src="' + item.link + '">',
'</label>',
'</div>',
'</div>'));
$grid.append( $items ).packery( 'appended', $items );
$grid.imagesLoaded().progress( function() {
$grid.packery();
$('body').on('change', '.grid .thumbnail :checkbox', function () {
var urls = [];
$(':checkbox:checked').each(function () {
urls.push($(this).next('label').find('img').attr('src'));
});
var str = '';
urls.forEach(function (url) {
str += '<div class="col-xs-12 col-md-6 grid-item"><div class="thumbnail"><img onerror="hideContainer(this)" src="' + url + '"/></div></div>';
});
$('#usp-custom-4').val(str);
});
});
});
});
_start += imagesCount;
}
}
var googleImagesFront = createGoogleImagesLoad();
googleImagesFront();
}
Are you calling loadImage() twice? That's the problem, it regenerates the uniqueId function each time, resetting counter to 0. Move the uniqueId function outside of loadImage and it should fix it.
If you want an unique id you can use this library that implements the standard RFC4122, its use is very simple, you need just add the library and choose the method of the version that you want generate:
console.log('UUID v1:', uuid.v1());
console.log('UUID v4:', uuid.v4());
<script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.7/uuid.min.js"></script>
The variable counter is always getting initialized when you are calling the function. If you place var counter = 0; this variable globally or outside the function then you should be able to get unique ids.

Cannot set property 'innerHTML' of null in javascript

guys i have a column which contains text and button and what i want is when click on the button the text changed .. here is my code
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText();"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText() {
document.getElementById("txt_" + count).innerHTML = "hey";
}
so why it gives me that exception ? .. plz help .. btw i am beginner
the count inside setText is undefined.
1st change onclick function of button to pass the count variable
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
then accept the count as parameter
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}
You can pass count to the function:
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}

loop through div with different elements

I generated elements and put them in MyDiv
$("#MyDiv").append('<input type=text class = "form-control" id=tb' + row.PropertyName + ' ' + 'value="Text' + row.PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">');
Now I need to extract the row.PropertyName and row.PropertyId
I need something like this:
var arrText = new Array();
$('#MyDiv > input[type = text]').each(function () {
var id = $(this).id.val();
var text = $(this).text.val();
var data = {
'id': id,
'text': text
}
I guess this is what you want.
$(function(){
var PropertyName = "pn1";
var PropertyId = "pn2";
$("#MyDiv").append('<input type="text" class = "form-control" id="tb"' + PropertyName + ' ' +
'value="Text' + PropertyName + '" />');
$("#MyDiv").append(' <input type="hidden" name="hid" value= "' + PropertyId + '">');
$('#MyDiv > input[type = "text"]').each(function(){
var id = $(this).val();
var text = $(this).next('input[type = "hidden"]').val();
var data = {
id: id,
text: text
}
alert(data.id + data.text);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="MyDiv"></div>
var arrText = [];
$('#MyDiv > input[type=text]').each(function () {
arrText.push({
'id': this.id,
'text': this.value
});
});
console.log( arrText );

Js/jQuery - How to hide/show an input created on the fly?

This code creates a group of elements (four inputs) on the fly. Once you create an element (four inputs) you can select/deselect, when you select an element will bring up the editor for the corresponding element. I've made a function to hide only the first element. The problem is that I can not make it comeback without affecting the other elements.
Instructions:
Click on the "Price" link, an element will be created on the fly (four nested inputs)
Select the element (four nested inputs) to bring up the editor ( one input and a brown little square).
Click on the little brown square to hide the first input of the element (four nested inputs) and that will hide the first input.
I need the little brown square to hide and show the same input.
Go here to see the full code:
To see the problem you have to create more than one element to find out.
http://jsfiddle.net/yjfGx/13/
This is the JS/jQuery code, for the full code go to the link above.
var _PriceID = 1;
$('#Price').on('click',function(){
var label = 'Price'
var Id = 'Price_';
var P = $( '<p class="inputContainer" />' ).fadeIn(100);
var l = $( '<label />' ).attr({'for':Id + _PriceID, 'id':Id + _PriceID, 'class':'priceLb'}).text( label ).after('<br/>');
var l1 = $( '<span class="dollar-sign" />' ).text( '$' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input1 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs',
'maxlength':'3', 'placeholder':'one',
'id':Id + _PriceID, 'class':'pricePh-1' })
.css({ "width":"60px", "paddingLeft":"1.3em", "paddingRight":"0.2em", "margin":"3px" });
var l2 = $( '<span class="priceComma-1" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input2 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'two', 'id':Id + _PriceID, 'class':'pricePh-2' })
.css({ "width":"68px", "paddingLeft":"0.7em", "paddingRight":"0.2em", "margin":"3px" });
var l3 = $( '<span class="priceComma-2" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input3 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'three', 'id':Id + _PriceID, 'class':'pricePh-3' })
.css({ "width":"64px", "paddingLeft":"1em", "paddingRight":"0.2em", "margin":"3px" }); var l4 = $( '<span />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input4 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'2',
'placeholder':'four', 'id':Id + _PriceID, 'class':'pricePh-4' })
.css({ "width":"37px", "paddingLeft":"0.5em", "paddingRight":"0.2em", "margin":"3px" });
P.append( l, l1, input1, l2, input2, l3, input3, l4, input4);
var D = $( 'form' );
P.on({
mouseenter: function() {
$(this).addClass("pb");
},
mouseleave: function() {
$(this).removeClass("pb");
}
});
P.appendTo(D);
_PriceID++;
});
/*** Select element individually and load editor. ***/
var flag = false;
$("form").on("click", "p", function () {
var cur = $(this).css("background-color");
if (cur == "rgb(255, 255, 255)") {
if (flag == false) {
$(this).css("background-color", "#FDD");
LoadPriceProperties($(this));
flag = true;
}
} else {
$(this).css("background-color", "white");
$('.properties-panel').hide();
flag = false;
}
});
/*** Element editor ***/
var LoadPriceProperties = function (obj) {
$('.properties-panel').css('display', 'none');
$('#priceProps-edt').css('display', 'block');
var label = $('.priceLb', obj);
var price1 = $('.pricePh-1', obj);
var price2 = $('.pricePh-2', obj);
$('#SetPricePlaceholder-1').val(price1.attr('placeholder'));
$('#SetPricePlaceholder-2').val(price2.attr('placeholder'));
/*** Getting an answer, depending on what they click on. ***/
$('#fieldOptionsContainer_1 div').bind('click', function () {
if ($(this).hasClass('field-option-delete')) {
RemoveUnwantedPriceField1($(this));
} else {
/*** Function loacated on "line 98" ***/
HideUnwantedPriceField_1($(this));
}
});
_CurrentElement = obj;
};
function HideUnwantedPriceField_1() {
var input = $('.pricePh-1', _CurrentElement);
var comma = $('.priceComma-1', _CurrentElement);
if($(input).is(":hidden")){
} else {
input.hide();
comma.hide();
}
}
Do you mean something like this: http://jsfiddle.net/Zaf8M/
var items=$('.m>li'), set= $('.set input'), num=0, item=$('.item'), list=$('.list');
item.hide();
items.click(function(){
$(this).addClass('sel').siblings().removeClass('sel');
num=$(this).index()+1;
set.prop( "disabled", false );
});
$('.close').click(function(){alert(3);});
$(window).click(function(e){
if( e.target.className=='sel' || e.target.type=='text'){return;}
else {
items.removeClass('sel'); set.prop( "disabled", true );
}
if(set.val()!='') {
item.clone().show()
.appendTo(list).children('.n').text(num)
.siblings('.p').text(set.val());
set.val('');
}
if( e.target.className=='close' ){$(e.target).parent().remove();};
});

Categories

Resources