I'm attempting to use .on() to add a text field when a dynamically created button is clicked. However, for whatever reason, I can't seem to get it working. Anyone see what's wrong? Thanks for any help and sorry if it's something obvious (I'm afraid that it might be but I just can't see it).
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Changes I made
► Declared variable prs as a global variable
► Remove # from the New Person button's id.
Working Demo
var prs = '';
$('#the-basics input.typeahead').keyup(function() {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example">
<div id="the-basics">
<input class="typeahead">
</div>
<div class="new_person new_fields">
</div>
</div>
Remove # from the New Person button's id.
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
Declare prs outside the click event like following.
var prs;
$('#the-basics input.typeahead').keyup(function () {
prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
var prs = $(this).val().split(' ');
is not a global variable, and inaccessible inside $('div#example').on('click', '#addpersonbutton', function() { so duplicate it inside your second function
EDIT: to make it clear:
$('#the-basics input.typeahead').keyup(function() {
var prs = $(this).val().split(' ');
if (!$("#the-basics span.newEntityButtons").length) {
var $newEntity = $('<span class="newEntityButtons">' + '</span>');
$newEntity.appendTo($("#the-basics"));
var $newPerson = $('<input type="button" value="New Person" id="addpersonbutton" class="newHolder newPerson" />');
$newPerson.appendTo($("span.newEntityButtons"));
}
});
$('div#example').on('click', '#addpersonbutton', function() {
var prs = $(this).val().split(' ');
var epo = new Date().getTime();
var theelement = '<span class="nested-fields person">' +
'<input id="stockholder_people_attributes_' + epo + '_fname" name="stockholder[people_attributes][' + epo + '][fname]" value="' + prs[0] + '">' +
'<a class="glyphicon glyphicon-trash remove_fields existing" href="#"></a>' +
'</span>';
$('div.new_person.new_fields').prepend(theelement);
});
Related
I am trying to outsource my inline javascript into an external one. The inline code looks like this and it works fine.
<script type="text/javascript">
$.getJSON('../servlets/solr/select?q=mods.genre:issue_a&state:published&rows=1&
fl=returnId,id,search_result_link_text,parentLinkText,mods.title&sort=modified
desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let ausgabe = "Ausgabe: ";
let titelmain = doc['search_result_link_text'];
let titelall = doc['mods.title'];
for (let i=0, item; item=titelall[i]; i++) {
if (item.indexOf(titelmain)>=0) {
titelall.splice(i,1);
}
}
let titel = titelall.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<span class="fa fa-arrow-right text-info" />' + ' ' +
'<span style="font-weight:bold">' + (doc['parentLinkText']) +
'</span>' + '<br/>' + '<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['returnId']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + titel + '</p>' + '<p/>')
);
});
});
</script>
The external javascript (new.js) looks like this.
It is stored inside the same folder as the html (index.html) invoking it.
$(document).ready(function(){
jQuery.getJSON('http://localhost:8282/mir/servlets/solr/select?q=mods.genre:journal&state:published&rows=2&fl=id,search_result_link_text,mods.title,mods.title.main,sb_amt,sb_ort&sort=modified desc&wt=json',
function (data) {
$(data.response.docs).each(function(i, doc){
let amt = doc['sb_amt'] ? doc['sb_amt'] : ' ';
let ort = doc['sb_ort'] ? doc['sb_ort'] : ' ';
let alletitel = doc['mods.title'];
let titel = alletitel.slice(1);
titel = titel.join(' ' + '|' + ' ');
let meta = [titel,amt,ort];
let text = meta.join(' ' + '|' + ' ');
$('#periodicals').append($('<div class="modified"></div>')
.append('<p class="lastmod-p interline text-content">' +
'<a class="navbar-link" style="font-weight:bold" href="../receive/'+doc['id']+'">' + doc['search_result_link_text'] + '</a>' + '<br/>' + text + '</p>')
);
});
});
alert('New Documents');
});
I added alert to be sure that the external javascript is beeing resolved.
The alert text pops up correctly but there is no data displayed.
In my HTML Code I have this:
<script src="new.js"></script>
<div class="col-md-4">
<h4 class="text-dark font-weight-bold" style="">PERIODICALS</h4>
<div id="periodicals"></div>
<a style="vertical-align:top" href="../servlets/solr/select?q=mods.genre:journal&
state:published&sort=modified desc"></a>
</div>
I'm wanting to get the key value pair for a the specific div, and only the div that I click on. Right now it is logging the values for each div. How can I get only the value for the specific div that I am clicking on? I'm wanting to update during an ajax success, but I'm stumped as to how to update only a certain div. Any ideas as to how I can do this?
$('.wrapper').on('click', '.bet-button', function() {
var self = $(this);
var gameId = self.attr('gameid');
var awayVal = $('#' + gameId + ' input[name=betAmountAway]').val();
var homeVal = $('#' + gameId + ' input[name=betAmountHome]').val();
var awayId = $('#' + gameId + ' .bet-input-away').data('away-id');
var homeId = $('#' + gameId + ' .bet-input-home').data('home-id');
var pointTotals = $('#' + gameId + ' .total-points').val();
console.log(pointTotals);
var value = awayVal || homeVal;
var id, value;
if (awayVal) {
id = awayId;
value = awayVal;
}
if (homeVal) {
id = homeId;
value = homeVal;
}
if (!value) {
alert('please enter a value!')
} else {
$.ajax({
url: "---------" + userId + "/"+ gameId +"/"+ id +"/"+ value +"",
type: "get",
success: function(response) {
// Makes the inputs inputable again.
$('.bet-input-home').prop('disabled', false);
$('.bet-input-away').prop('disabled', false);
function update(){
var currentSelection = $('#team-select').val();
getGames().done(function(results){
$.each(results, function (i, gameData){
$.each(gameData, function(key, game){
var gamesHome = game.home_team_conference;
var gamesAway = game.away_team_conference;
if(gamesHome == currentSelection || gamesAway == currentSelection){
var gameId = game.id;
var pointTotal = game.total_points_bet;
var gameTime = game.game_time_hour;
var gameDate = game.game_time_date;
var homeId = game.home_team.id;
var awayId = game.away_team.id;
var homePoints = game.total_points_bet_on_hometeam;
var awayPoints = game.total_points_bet_on_awayteam;
var totalPoints = homePoints + awayPoints;
// $('#point-total').append(homePoints + awayPoints);
}
});
});
})
}
update();
This updates html code that is generated dynamically (or at least it is supposed to)
$('.wrapper').append('\
<div id="'+ gameId +'" class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
<div class="game-cards">\
<div class="chart-container">\
<canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
</div>\
<div class="right-info">\
<h4>' + awayTeam + '<br>' + " # " + '<br>' + homeTeam +'</h4>\
<h5 id="time-channel">'+ gameDate +' # ' + gameTime + '<br>' + ' On ' + network +'</h5>\
<div class="total-points-live">\
<h5>Total Points Bet</h5>\
<h5 class="total-points" id="point-total">'+ totalPoints +'</h5>\
<p>'+ awayTeam +'</p>\
<input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
<p>'+ homeTeam +'</p>\
<input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
<p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
</div>\
</div>\
</div>\
');
How can I pass object to inline onclick event. When I try following code I either get undefined or [object object].
also how can I bind click event to h to avoid inline code.
this.get = function(o) {
console.log(o, o.foo);
}
this.somefunction = function(robj) {
for (var i = 0, i <= robj.length; i++) {
var fname = robj[i]['filename']
h += '<div class="checkbox checkbox-success" onclick="get(\'' + robj + '\')">' +
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>' +
'</div>';
}
}
A few problems I saw with your code,
your loop should be i < robj.length and has a syntax error , should be ;
h was not defined but now not used anymore
The array passed into get() cannot be accessed by using o.foo
Side note: take a look at ES6 template literals to help clean up some of the quoting action you are currently doing, for example id="' + fname + '" can look like id="${fname}"
Here is a full working example with the fixes above on how you can add a listener to your div (by creating DOM element) and with the object as a parameter.
this.get = function(o) {
console.log(o);
console.log(o.foo);
}
this.somefunction = function(robj) {
for (let i = 0; i < robj.length; i++) {
var fname = robj[i]['filename']
var myDiv = document.createElement("div");
myDiv.className = "checkbox checkbox-success";
myDiv.onclick = function(){get(robj[i])};
myDiv.innerHTML =
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>';
document.getElementById("container").appendChild(myDiv);
}
}
var robj = [{filename: "myFilename", foo: "myFoo"}]
somefunction(robj);
<div id="container"></div>
here is an example of dynamically written onclick . simply keep the function outside of doucment.ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changePath(distinct_inputs)
{
console.log(distinct_inputs);
}
$(document).ready(function(){
var distinct_inputs = 0;
$('.icon1').click( function(){
distinct_inputs = distinct_inputs + 1 ;
$('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});
});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>
</body>
</html>
I am adding and removing <ul> and placing its plain structure with its text into a textarea. The following works yet it is not closing all the <ul>s, not adding the closing </ul> basically but it places an open <ul> instead.
Here it is a jsFiddle
This is what I am doing:
HTML
<div id="mindMap">
<ul>
<li><button class="btn btn-default ul-appending">+ Node</button> </li>
</ul>
</div>
<div id="mindMapData">
<textarea col="10" rows="10"></textarea>
</div>
The in jQuery I am creating the tool to add/remove nested list and cleaning all the unnecessary html while leaving all the plain nested list and its text:
$('body').on('click', 'button.ul-appending', function() {
$(this).parent().append(
$('<ul class="main_ul">').addClass('newul sortable').append(
$('<li><div class="input-group"><input placeholder="Add node..." class="form-control" type="text"><div class="input-group-btn"><button type="button" class="btn btn-default list">+ sub node</button><button type="button" class="btn btn-default removeThis">remove</button></div></div></li>')
)
);
});
$('body').on('click', 'button.list', function() {
var newLi = '<ul class="sub_ul"><li class="listSub"><div class="input-group"><input placeholder="+ sub node..." class="form-control" type="text"><div class="input-group-btn"><button type="button" class="btn btn-default list">+ sub node</button><button type="button" class="btn btn-default removeThis">remove</button></div></div></li></ul>';
var listEl = $(this).parent().parent().parent();
$(listEl).append(newLi);
});
$('body').on('click', 'button.removeThis', function() {
$(this).parent().parent().parent().remove();
});
function ul(indent) {
indent = indent || 4;
var node = $(this);
return node.removeAttr('class').children().map(function() {
var self = $(this);
var value = self.find('> .input-group input').val();
var sub_ul = self.find('> ul');
var ul_spaces = new Array(indent+4).join(' ');
var li_spaces = new Array(indent).join(' ');
if (sub_ul.length && ul) {
return li_spaces + '<li>' + value + '\n' + ul_spaces +
'<ul class="sortable">\n' + ul.call(sub_ul, indent+8) + '\n' + ul_spaces + '<ul>\n' +
li_spaces + '</li>';
} else {
return li_spaces + '<li>' + value + '</li>';
}
}).get().join('\n');
}
function updateTree() {
$("#mindMapData textarea").text('<ul class="sortable">\n' + $("#mindMap").clone().find('.main_ul').map(ul).get().join('\n') + '\n</ul>');
}
$("#mindMap").on("DOMSubtreeModified", updateTree);
$("#mindMap").on('keyup', 'input', updateTree);
jsFiddle
Line 30:
'<ul class="sortable">\n' + ul.call(sub_ul, indent+8) + '\n' + ul_spaces + '<ul>\n' +
Correction:
'<ul class="sortable">\n' + ul.call(sub_ul, indent+8) + '\n' + ul_spaces + '</ul>\n' +
You need a slash here: '</ul>\n'
JSfiddle
I would like to make the text bold by clicking a button. See below code, the problem I'm having is that I'm unable to pass the textarea ID to the boldTF() function.
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<script>
$(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="Type Here"/>' + '<br /><button type="button" onclick="boldTF("field_' + tfCont + '")">Bold</button>' + '<br>' + '</div>' + '</div>');
x++;
return false;
});
function boldTF(tmp){
document.getElementById(tmp).style.fontWeight = "bold";
//alert(tmp);
};
});
</script>
Thank you.
Remove the inline event handler and use event delegation:
$(document).on('click', 'button', function () {
$(this).closest('div.name').find('input').css('font-weight', 'bold')
})
jsFiddle example
Many issues
<input type="textarea" should be <input type="text" or <textarea ...></textarea>
Use the class to get at the field
No need to mix DOM access with jQuery
jQuery can attach event handlers on dynamically created objects using delegation.
Working fiddle
$(function () {
$("#tfButton").on("click", function(e) {
e.preventDefault;
var tfCont = InputsWrapper.length;
$("#InputsWrapper").append(
'<div class="name" id="InputsWrapper_0' + tfCont + '">' +
'<input type="text" id="field_' + tfCont + '" class="fTypex" placeholder="Your first name"/>' +
'<br /><button type="button" class="boldTF">Bold</button><br /></div>');
});
$("#InputsWrapper").on("click", ".boldTF", function(e) {
e.preventDefault();
$(this).parent().find(".fTypex").css({"font-weight":"bold"});
});
});