I have a document that uses the jscolor.com library, for the user to be able to select and store a color. I'm also using a JQuery function to add rows to the screen, so the user can create and define a number of colors. The problem is, when the new row is added, the Javascript isn't re-initialized for the added elements.
Here is the code in question:
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<div id='addr" + i + "'>" +
"<div class='col-xs-4'>" +
"<input type='text' name='config_color[" + i + "][css]' id='input-color[" + i + "][css]' class='form-control' />" +
"</div>" +
"<div class='col-xs-2'>" +
"<input type='text' name='config_color[" + i + "][value]' id='input-color[" + i + "][value]' class='form-control jscolor' />" +
"</div>" +
"<div class='col-xs-2'>" +
"<input type='text' name='config_color[" + i + "][default]' id='input-color[" + i + "][default]' class='form-control' />" +
"</div>" +
"<div class='col-xs-4'>" +
"<input type='text' name='config_color[" + i + "][notes]' id='input-color[" + i + "][notes]' class='form-control' />" +
"</div>" +
"</div>");
$('#tab_logic').append('<div id="addr'+(i+1)+'"></div>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
}).trigger('change');
</script>
I've made an simplified example of what I'm talking about on JSFiddle - you can see in the first row, if you click in the color cell, it gives you a pop up color palette.
If you add additional rows, the popup picker doesn't work.
However, all of the data stores in the database properly, so i have an instance where some elements added by Javascript work properly and others don't?
(Also full disclosure, I asked on Reddit first - this is therefore a cross-post.
In their examples, jscolor has one called "Instantiating new Color Pickers" which shows you how to do it.
You're adding the new row as a string, which I wouldn't recommend, because if you created each input separately using jQuery it would be easier to call jscolor() on only one element, but this works too.
Just add the following to your click handler:
// Get all the inputs first
var allInputs = $('.jscolor');
// From there, get the newest one
var newestInput = allInputs[allInputs.length - 1];
// And call jscolor() on it!
new jscolor(newestInput);
Here's an updated fiddle
Generally Abe Fehr answer helped me too, but i had slightly other problem. My elements already had default values from database so
new jscolor(newestInput);
initialized them but with default FFFFF
So in my case twig (html) looks like this:
<button class="jscolor {value:'{{ category.color }}'} btn btn-sm disabled color-picker" data-color="{{ category.color }}"></button>
And then I reinitialize all the colors like this:
let all_pickers = $('.color-picker');
if ($(all_pickers).length !== 0) {
$(all_pickers).each((index, element) => {
let color = $(element).attr('data-color');
new jscolor(element, {'value': color});
});
}
Related
I have a form I enter student info (name, email, address) and I was able to add a new row (made of three columns) using JS after I click a button. Every time a new row is created, three new columns are created with three input boxes each with its own element ID. So far so good. However, now I can't for the life of me figure out how to remove the last row that was added. Below is my code:
var student_ids = 0;
document.getElementById("studentCount").value = student_ids;
function anotherStudent(){
document.getElementById("student_info").innerHTML +=
"<div class='section colm colm4'>"+
"<input type='text' name='stud_name_" + student_ids + "'id='stud_name_" +student_ids+ "'class='gui-input' placeholder='Student name'>"+
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='email' name='stud_email_" + student_ids + "'id='stud_email_" + student_ids + "'class='gui-input' placeholder='Email'>" +
"</div><!-- end section -->" +
"<div class='section colm colm4'>" +
"<input type='text' name='stud_address_" + student_ids + "'id='stud_address_" + student_ids + "'class='gui-input' placeholder='Address'>"+
"</div><!-- end section -->" ;
student_ids = ++student_ids;
document.getElementById("studentCount").value = student_ids ;
}
function removeStudent(){
var x = document.getElementById('stud_name_'+student_ids);
var y = document.getElementById('stud_email_'+student_ids);
var z = document.getElementById('stud_address_'+student_ids);
x.remove();
y.remove();
z.remove();
}
Edit:
You are not removing the divs, only the inputs themselves. You are also incrementing the student_ids global variable after you insert a row. This means that the removeStudent() function will always try to remove a non-existing row.
It would be better to pass the desired student_ids to removeStudent(), or manually de-increment the value.
In older environments (such as Explorer):
You cannot directly remove DOM elements from JavaScript. It's a bit unintuitive, but you have to go to the parent of that element and remove it from there:
var element = document.getElementById('stud_name_'+student_ids);
element.parentNode.removeChild(element);
I have some jQuery script in which I'm adding some rows to a table (when the user press a button). My problem is that I want to change the id of the elements inside the rows dynamically. I have set a global variable i which I set as an id to some elements inside my table. The problem is that after some debugging I found out that the id doesn't change at all and stays as the letter i (and not the variable i set to 0 and increase every time the user press the button). Any ideas?
var i=0;
var a1=i.toString().concat("1");
var a2=i.toString().concat("2");
var a3=i.toString().concat("3");
$("#table1").append("<tr><td><center><input id=\"a1\"></input></center></td><td>
center><button id=\"a2\">Load</button></center></td><td ><img id=\"a3\"></td>
</tr>");
$("#a2").click(function(){
$z=$("#a1").val();
$("#a3").attr("src",$z);
i++;
});
That's because you're writing those directly as strings. You need to concatenate them into the actual string. You can concatenate strings together using +.
$("#table1").append(
"<tr>" +
"<td>" +
"<center><input id=\"" + a1 + "\" /></center>" +
"</td>" +
"<td>" +
"<center><input id=\"" + a2 + "\" /></center>" +
"</td>" +
"<td>" +
"<center><input id=\"" + a3 + "\" /></center>" +
"</td>" +
"</tr>"
);
For what it's worth, the <center> tag is deprecated and should not be used. You may also consider creating some kind of template rather than generating your HTML as strings directly inside of JavaScript.
I'm making a small website for school, it's an image based gallery where you can vote and comment.
At the moment they're all on one page and all have a rating form.
So at the moment the default rating is working, but I cant update it (I frankly don't know how)
Here's how it looks now
http://i.imgur.com/M4ZOtUG.png
The user is supposed to enter a rating, and then it should show the new value of the rating.
I'm pretty close since when I rate the first image 3; I get: (in my console)
"c1, 3"
And when I rate the 4th image 5, I get:
"c4, 5"
etc.
Now how do I update the default rating?
(default ratings are set in my collection)
Example code of image in collection
{image: "images/gifs/water.gif", rating: 5, comments: "Love the detail in this one!", title:"Water", category:"Nature"}
Here's how it's in my view:
gifs_html += '<td>' + "<span class=\"stars\">" + gifs[gif].get("rating") + ".0</span>" + "\n" + "<form data-id=\"" + gifs[gif].cid + "\"><input type=\"text\" name=\"amount\" size=\"5\" value=\"\"/>" + "\n" + "<input type=\"submit\" value=\"Rate\">" + "<input type =\"hidden\" name=\"cid\" value=\"" + gifs[gif].cid + "\"> </form>" + '</td>';
Then I'm giving this jquery function (to update the star image)
$('span.stars').stars();
and this event
events:{
'submit form':function(ev){
var $form = $(ev.currentTarget);
var id = $form.data("id");
var rating = $("input[name=amount]", $form).val();
console.log(id + ", " + rating);
return false;
}
Help would be greatly appreciated. Thanks.
If the view where you are setting that 'submit form' event it's a Collection View you have to do something like this:
this.collection.get(id).set("rating", rating);
If it would be a Model View:
this.model.set("rating", rating);
Cheers.
This is the code which i use to append table row,where personTabs is the iframe name
$(".addClass1").on('click',function() {
parent.parent.parent.personTabs.$("#skilltableId").append(
'<tr id="skilltableId1"><td class="btnRemoving">'+$("#selecetedValue").val()+'</td><td class="editing">'+$("#type").val()+'</td><td style="display:none">'+$("#commonDbid").val()+'</td></tr><br>'
);
when i click td class='editing', i am generating a textbox as follows..
parent.parent.parent.personTabs.$(".editing").on('click',function() {
var data = $(this).text();
$(this).html("<input type='text' id='focus123' value='"+data+"'/>").children().focus();
});
I am getting everything fine for the first time..the table row is been appended fine..when i do the same append for the second time,table row is generated.onclick working only for the last generated row..but not previous one..why is it so..anybdy here can tel me,..i tried live,delegate methods..but none worked..i am using jquery-1.9.1.js
I think one problem is that you have created a text box with the same id.
I am not sure why you used parent.parent.parent...
$(".addClass1").on('click',function() {
$("#skilltableId").append(
'<tr id="skilltableId1"><td class="btnRemoving">'+$("#selecetedValue").val()+'</td><td class="editing">'+$("#type").val()+'</td><td style="display:none">'+$("#commonDbid").val()+'</td></tr><br>'
);
$(".editing").on('click',function() {
var data = $(this).text();
$(this).html("<input type='text' class='focus123' value='"+data+"'/>").children().focus();
});
I am not sure if it will work or not, but you can also use this javascript function
$(".addClass1").on('click', function () {
$("#skilltableId").append('<tr id="skilltableId1"><td class="btnRemoving">' + $("#selecetedValue").val() + '</td><td class="editing" on click="myfunction(this)">' + $("#type").val() + '</td><td style="display:none">' + $("#commonDbid").val() + '</td></tr><br>');
function myfunction(selectedTd) {
var data = $(selectedTd).text();
$(selectedTd).html("<input type='text' class='focus123' value='" + data + "'/>").children().focus();
}
});
I'm just new here. So here's where I'm stuck:
I created an html table using javascript. I have a button,which when clicked, will create set of tables with exactly the same structure but the objects(eg. button, text) inside those tables have different ID's. Now when I try to execute a click function using jQuery with a button on one of the produced tables, it won't work. How do I go around here? Thanks in advance!
Here's a sample function which creates the html table(with unique ID's) in javascript:
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
document.getElementById('HtmlPlaceHolder').innerHTML = html;
}
So, if we review the code, Sets of table with buttons(btnALERT) with unique ID's will be created if the function CreateTables is executed. In order to select the objects, I suppose I'll be using jQuery. So for example, if I bind a handler in btnALERT1(produced by CreateTables) say a click function in order to alert a simple "Hello", how will I do this? My code for this doesn't seem to work:
$(document).ready(function() {
$('#btnALERT1').click(function() {
alert("Hello");
});
});
Use .live() (for older jquery versions - < v1.7):
$('#btnALERT1').live('click', function()
{
alert("Hello");
});
Or:
$(document).delegate('#btnALERT1', 'click', function()
{
alert("Hello");
});
Use .on() (for new jquery versions - >= 1.7):
$(document).on('click', '#btnALERT1', function()
{
alert("Hello");
});
I think you may want to use the method .on():
$(document).ready(function() {
$('#btnALERT1').on('click', function() {
alert("Hello");
});
});
For more information, check the online doc: http://api.jquery.com/on/
I would use a delegate on HtmlPlaceHolder to check for click events like so:
$("#HtmlPlaceHolder").on("click", "input[type=button]", function() {
alert($(this).attr("id"));
});
Also, I would change the button id scheme to btnALERT_1, so you can extract the ID number with a .split("_") method.
You have to attach the event handlers after you create the tables, not when the document is ready (the document should be ready anyways since the user is interacting with it).
You can do this with jQuery, sure, but have a look at the native methods - jQuery might be too bloated depending on what you will do and you will learn something about the DOM.
I've added some code below which lets you add a callback and shows some things you can get back easily. It is not exactly what you asked for, but a great start to finding your way in the DOM.
function CreateTables() {
var html = ' ';
var valPrompt = prompt("How many tables would you like to add?");
parseInt(valPrompt);
for (i = 1; i <= valPrompt; i++) {
html += "<table>" + "<tr>" + "<td>" + "Text goes here" + "</td>" + "<td>" + "<input type='text' id='txtTEXT" + i + "'/>" + "</td>" + "<td>" + < input type = 'button'
id = 'btnALERT" + i + "' / > +"</td>" + "</tr>" + "</table>"
}
var placeholder = document.getElementById('HtmlPlaceHolder').innerHTML = html;
placeholder.innerHTML = html;
placeholder.addEventListener('click', function (e) {
console.log(this, e);
}
}