Assigning classes or ids to button created dynamically using jquery - javascript

I am creating several buttons dynamically. I am trying to assign each on a different class or id so when it is clicked on it will have a different output. How would I add an value at the end of each class or id name to give each button a unique class or id name?
Here is my code
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for(i=0; i <data.length; i++){
$input = $('<input type="button" style="width:200px" class= "button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
});
Can I created an on click event for the all button that I created. So far I created an on click even, but it only works for the first button.
Here is my code
$(document.body).on('click','.button', function(e) {
console.log($('.button').val());
});

Use $(this).val() instead of $('.button').val(). this will refer clicked button.
$(document.body).on('click','.button', function(e) {
console.log($(this).val());
});

socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for(i=0; i <data.length; i++){
$input = $('<input type="button" id="btn"'+i+' style="width:200px" class= "button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
});

Problem: Is with this part of code console.log($('.button').val()); The part $('.button') selects all the buttons , But when you say .val() it defaults to the first one out of the collection. Hence you see the same output on all the button clicks.
Solution: Change the code to log the current clicked button value by using $(this).val(). this will refer to the element that triggered the event.
So the final line of code should be
console.log($(this).val());

Related

How to select element after it was added to DOM

On my HTML I have buttons list and text input field. Input field is to add extra buttons to my buttons list.
On jQuery I have eventListener when one of these buttons with .choices is clicked console log its value.
It works fine without any errors. But when I add extra button to my list with same class (.choices) new button appears but it doesn't respond to my click.
Any suggestions?
<div class="buttons">
<button id="button0" class="choices">Running</button>
<button id="button1" class="choices">Yoga</button>
<button id="button2" class="choices">Karate</button>
</div>
JS
$("#add-button").click(function(){
var inputValue = $("#add-input").val();
var generatedId = "button" + healthyChoices.length;
healthyChoices.push(inputValue);
$("<button>").attr("id", generatedId).appendTo(".buttons");
$("#" + generatedId).attr("value", inputValue);
$("#" + generatedId).attr("class", "choices");
$("#" + generatedId).text(inputValue);
$("#add-input").val("");
});
$(".choices").click(function(){
var selectedGroup = $(this).val();
console.log(selectedGroup);
});
The .click method does not handle elements dynamically added to the DOM. You should be using the .on method (as indicated by dfsq's comment).
See this SO post: Difference between .on('click') vs .click()

Same button for 2 tables selection jquery

i have a page and i got 2 tables in that page. I want to pass the value from rows to one .php page but with the same button. My code is this:
JS code:
var flag;
function highlight(e) {
if (selected[0]){
selected[0].className = '';
flag='1';
}
else if (selected2[0]){
selected2[0].className = '';
flag='0';
}
e.target.parentNode.className = 'selected';
alert(flag);
}
var table = document.getElementById('data-table'),
selected = table.getElementsByClassName('selected');
var table2 = document.getElementById('data-table-aux'),
selected2 = table2.getElementsByClassName('selected');
table.onclick = highlight;
table2.onclick=highlight;
$("#tst").click(function(){
if(flag=='1'){
var value =$(".selected td:first").html();
value = value || "Nenhuma coluna selecionada";
window.open("info_detalhada.php? data2="+value,'_blank','toolbar=0,location=no,menubar=0,height=550,width=650,lef t=200, top=300'); }
else if(flag=='0'){
var value =$(".selected td:first").html();
value = value || "Nenhuma coluna selecionada";
window.open("info_detalhada2.php? data2="+value,'_blank','toolbar=0,location=no,menubar=0,height=550,width=650,lef t=200, top=300');
}
});
HTML CODE
creating 2 tables
<table style="float: left" id="data-table"></table>
<table style="float: left" id="data-table-aux"></table>
(Dynamic tables )
button:
<input type="button" id="tst" value="Detailed information" />
The problem is that first time i select a row the variable flag will have the old value and not the new value from click.
For example, first time i click a row flag = undefined , second time got the value of the table selected (0 or 1) , if i click on other row the flag wont change and will got the old value (or 0 or 1).
Any tips ?
Thanks
edited: i didnt put the html in first place because i dont think it's an html solution, I dont have a fiddle created because i'm using dynamic table's but i will try to make a fiddle with my example and i will put here when it's done ;)
Fiddle : https://jsfiddle.net/gwg639Lf/9/
Let me suggest a more generic approach
First of all wrap your tables in a div
<div class="data-tables">
<table style="float: left" id="data-table"></table>
<table style="float: left" id="data-table-aux"></table>
</div>
Then delegate the click event handlers
$('.data-tables').delegate('table', 'click', function(event) {
$this = $(this)
$this.addClass('active').removeClass('inactive')
$this.siblings().addClass('inactive').removeClass('active')
});
This function does the following:
Add class active and remove inactive (if exists) to the selected item/table
Remove the class active and add class inactive from all adjacent tables
In this way you will only have one active table at the time
Then declare your button handler
$("#tst").click(function(){
var value = $('.active').html()
// Use the value as you want
})
This code will work no matter how many tables you add to the div
You're setting the class name of the element after the condition statement. Hence, the first time, your flag variable is undefined.
Try putting it in the beginning of the highlight function.
function highlight(e) {
e.target.parentNode.className = 'selected';
if (selected[0]){
selected[0].className = '';
flag='1';
}
else if (selected2[0]){
selected2[0].className = '';
flag='0';
}
alert(flag);
}
JsFiddle: https://jsfiddle.net/gwg639Lf/10/
Edit:
Add it before and after the condition. Adding it before the condition gives you the class name to initialize the flag variable. Adding it after gives the formatting bar.
JsFiddle: https://jsfiddle.net/gwg639Lf/13/
Ok, after some tests on Kostas Pelelis functions, i found a solution that is valid for my problem.
here is the code of JS:
var flag;
$("#data-table tr").click(function(){
$("#data-table-aux tr").addClass('selected').siblings().removeClass('selected');
$(this).addClass('selected').siblings().removeClass('selected');
flag='1';
});
$("#data-table-aux tr").click(function(){
$("#data-table tr").addClass('selected').siblings().removeClass('selected');
$(this).addClass('selected').siblings().removeClass('selected');
flag='0';
});
$('#tst').on('click', function(e){
if (flag=='1')
alert($("#data-table tr.selected td:first").html());
else if (flag=='0')
alert($("#data-table-aux tr.selected td:first").html());
});
Here is the fiddle --> fiddle
Thank you all for the help ;)

Click button to Edit Table titles

I have a table with Column title. There is also a edit button. If I click the button, Table title should be a Input field with title name as a value in it. Edit button will turn into Save Button.
I can rename the title and Save the new names. I not good in jquery and what I made creating bunch of input fields and I can't save new names. FIDDLE
Any help will save my day. Thanks in advance.
jQuery:
var textInfo = $('.table th').text();
$("html").on('click', '.btn-danger', function() {
$('.table th').append('<input id="attribute" type="text" class="form-control" value="' + textInfo + '" >');
$('.btn-danger').text('Save');
}) ;
Here is a fiddle that solves your problem.
http://jsfiddle.net/has9L9Lh/54/
It uses a common approach of toggling an element's class (or some other attribute), to determine the state of your program. In this case, it determines whether or not the columns are in edit-mode, and changes the button text and th html accordingly.
$("html").on('click', '.btn-danger', function() {
var editMode = $(this).hasClass('edit-mode'),
columns = $('.table th');
if (!editMode){
$(this).html('Save').addClass('edit-mode');
columns.each(function(){
var txt = $(this).text();
var input = $('<input type="text">');
input.val(txt);
$(this).html(input);
});
} else {
$(this).html('Edit').removeClass('edit-mode');
columns.each(function(){
var newName = $(this).find('input').eq(0).val();
$(this).html(newName);
});
}
}) ;
• you should not use id in the append this will create multiple id of the same name.
• use $(".form-control").length to check if it exist. this will solve multiple input when button is clicked multiple times.
• create a new button to submit your change.
• create another click event for the new button.
• than use it $.val() to get input value than pass that value to the new table title. and you are done.
I hope this will point you to the right direction. :D

Getting the value of a hidden field in <td> using jquery

I have a table data which is generated dynamically via a loop. The td contains a hidden field. below is the code for the same:
<td class="gridtd" id = "r<%=RowNumber%>c<%=ColumnNumber%>">
<input id="hiddendata" type="hidden" value="<%: item.Key%>"/>
</td>
I need to extract the value of the hidden field based on the td selected using jQuery. Please help me get the correct jquery code.
Just select your input and take the value (val()):
$("#hiddendata").val();
If you want to take all hidden input values:
$("input[type='hidden']").each(function () {
console.log($(this).val());
});
Note that the element ids must be unique.
I need to extract the value of the hidden field based on the td selected using jQuery.
If by select you mean, click, you can simply pass this when getting the value:
$("td").on("click", function () {
console.log(
$("[type='hidden']", this).val()
);
});
For your general knowledge, if you do $("#hiddendata", this).val(); inside of the click handler, it will return the correct value (even having multiple ids with the same value).
But definitely, the ids must be unique.
Use this :
$('#hiddendata').val();
$('td').click(
function(event)
{
$(event.target).find('#hiddendata').val();
}
);
It ll give the hiddendata value based on td selection
This will give the value of the hidden field for the selected td.
$('.gridtd').click(function(){
console.log($(this).find('input').val());
});
$('.gridtd').click(function(){
console.log($(this).find('input[type=hidden]').val());
});
You can try this:
$('.gridtd').each(function(){
var currentId = $(this).attr('id');
var hiddenval = $('#'+currentId).find('input[type=hidden]').val();
alert(hiddenval);
})

JS Events not attaching to elements created after load

Problem: Creating an Element on a button click then attaching a click event to the new element.
I've had this issue several times and I always seem to find a work around but never get to the root of the issue. Take a look a the code:
HTML:
<select>
<option>567</option>
<option>789</option>
</select>
<input id="Add" value="Add" type="button"> <input id="remove" value="Remove" type="button">
<div id="container">
<span class="item">123</span>
<br/>
<span class="item">456</span>
<br/>
</div>
JavaScript
$(".item").click(function () {
if ($("#container span").hasClass("selected")) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
$("add").click(function() {
//Finds Selected option from the Select
var newSpan = document.createElement("SPAN");
newSpan.innerHTML = choice;//Value from Option
newSpan.className = "item";
var divList = $("#container");
divList.appendChild(newSpan);//I've tried using Jquery's Add method with no success
//Deletes the selected option from the select
})
Here are some methods I've already tried:
Standard jQuery click on elements with class "item"
Including using the `live()` and `on()` methods
Setting inline `onclick` event after element creation
jQuery change event on the `#Container` that uses Bind method to bind click event handler
Caveat: I can not create another select list because we are using MVC and have had issues retrieving multiple values from a list box. So there are hidden elements that are generated that MVC is actually tied to.
Use $.on instead of your standard $.click in this case:
$("#container").on("click", ".item", function(){
if ( $("#container span").hasClass("selected") ) {
$(".selected").removeClass("selected");
}
$(this).addClass("selected");
});
It looks to me like you want to move the .selected class around between .item elements. If this is the case, I would suggest doing this instead:
$("#container").on("click", ".item", function(){
$(this)
.addClass("selected")
.siblings()
.removeClass("selected");
});
Also note your $("add") should be $("#add") if you wish to bind to the element with the "add" ID. This section could also be re-written:
$("#add").click(function() {
$("<span>", { html: $("select").val() })
.addClass("item")
.appendTo("#container");
});

Categories

Resources