Get Input in Div with Starting-ID - javascript

I would like to select a Input inside a Div which has a dynamic id ([id^="SML_ID_"]) is it possible to archive it?
My Example-Code is this:
$('[id^="SML_ID_"] .social_media_input_type').on("change", function() {
var Link_ID = $('[id^="SML_ID_"]').attr("id");
var Link_Type = $("SML_ID_" + Link_ID + " > social_media_input_type").text();
Link_ID.replace("SML_ID_", "");
$("SML_ID_" + Link_ID).text("Input a" + Link_Type + "link");
});
Any Idea?
EDIT:
HTML-Structure:
var Link_ID = 0;
$("#AddSocialMediaLink").on("click", function() {
Link_ID = Link_ID + 1;
var AddSML_HTML_String = '<div id="SML_ID_' + Link_ID + '" class = "social_media">\n\
<input class="social_media_input_type" type="text" placeholder="Input a Type!"/>\n\
<input class="social_media_input_link" name="" placeholder="Input a link" / >\n\
</div><br/>';
$("#social_media_form").prepend(AddSML_HTML_String);
})

Use delegation by attaching to a container
$(document).on('change','[id^="SML_ID_"] .social_media_input_type', function() {
var Link_ID = $('[id^="SML_ID_"]').attr("id");
var Link_Type = $("SML_ID_" + Link_ID + " > social_media_input_type").text();
Link_ID.replace("SML_ID_", "");
$("SML_ID_" + Link_ID).text("Input a" + Link_Type + "link");
});

Related

Delete Confirmation dialog in jQuery on dynamic content

My div contains records which are added dynamically. When I click on the 'Remove' link it generates a confirm box 3 times if I have 3 record, 5 times if I have 5 records and so on.
I want to display the confirm box for that particular row only. How can I do that?
```
<script type="text/javascript">
$(document).ready(function () {
$("#<%= imagehs.ClientID %>").on("click", function (event) {
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
var values = new Array();
var x = event.pageX;
var y = event.pageY;
//$(".marker").remove();
$("body").append(
// $('<div class="marker"></div>').css({
//$('<div class="marker m_' + x + '_' + y + '" divdata-marker="m_' + x + '_' + y + '"></div>').css({
$('<div class="marker m_' + x + '_' + y + '"></div>').css({
position: 'absolute',
top: y + 'px',
left: x + 'px',
//top: event.pageY + 'px',
//left: event.pageX + 'px',
width: '10px',
height: '10px',
background: '#dd4b39',
'border-radius': '10px'
})
);
$("#textboxX").append('<div><input type="text" value="' + x + '" id="txtX" name="txtX"/></div>');
$("#textboxY").append('<div><input type="text" value="' + y + '" id="txtY" name="txtY"/></div>');
$("#textboxBPart").append("<div><input type='text' id='txtName' name='txtName'/></div>");
var $r = $('<button />', { type: 'button', text: 'Refresh Data', id: 'btn_refresh' });
var $cancle = $('<button />', { type: 'button', text: 'Cancle', id: 'btn_cancle' });
$("#divSaveDynamicDis").append($r);
$("#divSaveDynamicDis").append($cancle);
$r.on('click', function () {
if ($('input#txtName').val() == "") {
alert('Please complete the field');
$('input#txtName').focus();
return false;
}
//var NewData = '<div cla-ss="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' <a href="javascript:void(0);" class="remCF" data-atrib=' + x +'>Remove</a> </div>';
//var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
$("#divdynamicData").append(NewData);
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
});
$('.marker').on('click', function () {
$(this).remove();
// div_ref = $(this).attr('divdata-marker')
// $('#divdynamicData.' + div_ref).remove()
});
//$("#divdynamicData").live('click', '.remCF', function () {
//$("#divdynamicData").on('click', '.remCF', function () {
// //if (confirm("Are you sure?")) {
// marker_ref = $(this).attr('data-marker')
// $('.marker.' + marker_ref).remove()
// $(this).parent().remove();
// //}
// //return false;
//});
$("#divdynamicData").on('click', '.remCF', function () {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
$cancle.on('click', function () {
$("#textboxX").html("");
$("#textboxY").html("");
$("#textboxBPart").html("");
$("#divSaveDynamicDis").html("");
});
});
});
```
$("#textboxX").append('<div><input type="text" value="' + x + '" id="txtX" name="txtX"/></div>');
$("#textboxY").append('<div><input type="text" value="' + y + '" id="txtY" name="txtY"/></div>');
$("#textboxBPart").append("<div><input type='text' id='txtName' name='txtName'/></div>");
var NewData = '<div class="col-sm-12">' + x + ' ' + y + ' ' + txtName.value + ' Remove </div>';
$("#divdynamicData").append(NewData);
$("#divdynamicData").on('click', '.remCF', function() {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6">
<asp:Image id="imagehs" name="imagehs" runat="server" Height="500" Width="500" />
<div id="textboxX"></div>
<div id="textboxY"></div>
<div id="textboxBPart"></div>
<div id="divSaveDynamicDis"></div>
<div id="divdynamicData"></div>
</div>
You're short circuting your code by returning the value of the confirm. In other words, once you return the value of confirm, none of the code below it will fire. Instead, you want to check what the user has chosen from the confirm via a conditional and place your removal code in the proceeding block:
$("#divdynamicData").on('click', '.remCF', function() {
if (confirm("Are you sure you want to delete?")) {
var marker_ref = $(this).attr('data-marker');
$('.marker.' + marker_ref).remove();
$(this).parent().remove();
}
});
I assume you are using this code inside a loop or inside another event. The code below should be removed from this loop/event and only be used one time in your page:
$("#divdynamicData").on('click', '.remCF', function () {
// if (confirm("Are you sure you want to delete?")) {
marker_ref = $(this).attr('data-marker')
$('.marker.' + marker_ref).remove()
$(this).parent().remove();
// }
});
Because it is a delegate click, each time you declare this code, a new event listener will be attatched to your div listening to clicks on .remCF so multiple events will be fired on your click.
See more: JQuery API .on()

How to update div content by changing panel name

When I edit panels name I want to update div content, that will have tab-pane name.
I tried to get the value and change it "onchange", but
I think I did something incorrectly.
http://jsfiddle.net/agata666/5zLmtqby/139/
var $foo = $(".tab-pane");
var $newPanelDefault = $foo.clone();
var hash = 1;
$(".add").on("click", function() {
var $newPanel = $newPanelDefault.clone();
var hashClass = 'zone-panel-' + generateHash();
$newPanel.find(".panel").data('hash', hashClass).attr("href", "#" + (++hash)).text("Zone " + hash);
$newPanel.attr("id", "tab" + hashClass);
var nextTab = $('.tabs li').size()+1;
$('<li class="' + hashClass + '">Zone ' + hash + ' <i class="fas fa-pencil-alt pencil"></i></li>').appendTo('.tabs');
$($newPanel).appendTo('.tab-content');
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
});
var panelDefault = document.querySelectorAll('.panel-default');
var exTabFirst = document.querySelectorAll('.exTabFirst');
var exTabSecond = document.querySelectorAll('.exTabSecond');
var addZoneButton = document.getElementById('add');
function generateHash() {
return Math.random().toString(16).substr(-5);
}
addZoneButton.addEventListener('click', function () {
var randomNumber = generateHash();
panelDefault.innerHTML = 'panel panel-default foo template ' + randomNumber;
exTabFirst.innerHTML = 'exTabFirst ' + randomNumber;
exTabSecond.innerHTML = 'exTabSecond ' + randomNumber;
});
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
Could you help me?

Dynamic select drop down box returning null or undefined

I am trying to achieve a dropdown box in my webpage which lists the options from the values in the database. I have achieved showing the listed options for the dropdown, but when I select the option it is not set to a value. In other words I have a doubt whether my dropdown is initialized or not.
I have added the required snippet for the action.
function add_row() {
table = document.getElementById('b_book');
var rowData = document.createElement('tr');
rowData.innerHTML = '<td>' + slno +
'</td><td id="dbSNO"><select id="SNO[' + slno + ']" onchange="detail_fetcher(this.value)" onselect="detail_fetcher(this.value)" onload="detail_fetcher(this.value)"></select></td>' +
'<td id="dbLNO"><input type="text" id="LNO[' + slno + ']" list="lot_srch_list" onkeydown="LNO_COL(event,this.value,this.id)" onfocus="lotNo_select()"/></td>' +
'<td><input type="text" id="dbMTR[' + slno + ']"/></td><td id="dbWT[' + slno + ']"></td><td id="dbMWT[' + slno + ']"></td><td id="GPM[' + slno + ']"></td><td id="dbTONE[' + slno + ']"></td><td><button id="btn_rem[' + slno + ']" onclick="remove_row()">Remove</button></td>';
table.appendChild(rowData);
slno += 1;
}
function LNO_COL(e, lno, hashtag) {
var beg_pos = hashtag.indexOf('[') + 1;
var end_pos = hashtag.indexOf(']');
var hash_pos = hashtag.substring(hashtag.lastIndexOf('[') + 1, hashtag.lastIndexOf(']'));
var postIN = 'par=' + parname.value + '&lno=' + lno;
if (e.ctrlKey) {
sNo_list = document.getElementById('SNO[' + hash_pos + ']');
sNo_list.innerHTML = '';
var XMLhLNO = new XMLHttpRequest();
XMLhLNO.onreadystatechange = function () {
if ((this.readyState === 4) && (this.status === 200)) {
var result = this.responseText;
var JSON_result = JSON.parse(result);
for (z in JSON_result) {
var sno_opt;
sno_opt = document.createElement('option');
sno_opt.value = JSON_result[z].slno;
sno_opt.text = JSON_result[z].slno;
sNo_list.appendChild(sno_opt);
}
}
};
XMLhLNO.open('POST', 'sno_lot_par2.php', true);
XMLhLNO.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
XMLhLNO.send(postIN);
detail_fetcher(hashtag);
}
}
function detail_fetcher(hash_position) {
var row_no = hash_position.substring(hash_position.lastIndexOf('[') + 1, hash_position.lastIndexOf(']'));
var serial_row = document.getElementById('SNO[' + row_no + ']');
alert(serial_row.);
/* var XMLfetcher = new XMLHttpRequest();
XMLfetcher.onreadystatechange = function()
{
if((this.readyState == 4)&&(this.status == 200))
{
var src_result = this.responseText;
var JSON_res = JSON.parse(src_result);
alert(serial_row_db);
alert(src_result);
}
};
XMLfetcher.open('POST','srch_lot2.php',true);
XMLfetcher.setRequestHeader('Content-type','application/x-www-form-urlencoded');
XMLfetcher.send(('row=' + serial_row_db));
*/
}
I have tried using value method, selecteditem(index) method but none of them proves to be successful.
Note: I want to use pure JavaScript as I am quite confused with using jQuery.

Can't get json object

I am trying to get city name from input element and then get the weather information and also timezone information of the city from API.
However i can't get the json object in that function but it works outside the function.
Can anyone help me?
var d = "Lisbon";
$(document).ready(function() {
$("#button").click(function() {
d = document.getElementById("input").value;
$(document).ready(function myfunction() {
$.getJSON('http://api.openweathermap.org/data/2.5/weather?APPID=11d324c05e02e308c1c9eb8d8041b143&q=' + d + '&units=metric', function(data) {
document.getElementById("city").innerHTML = data.name + ", " + data.sys.country;
document.getElementById("wind").innerHTML = data.wind.speed + " m/s ";
document.getElementById("cloudiness").innerHTML = data.weather[0].description;
document.getElementById("pressure").innerHTML = data.main.pressure + " hpa";
document.getElementById("humidity").innerHTML = data.main.humidity + " %";
document.getElementById("coord").innerHTML = "[ " + data.coord.lat + ", " + data.coord.lon + " ]";
document.getElementById("temperature").innerHTML = data.main.temp + "°C";
document.getElementById("icon").innerHTML = "<img src=http://openweathermap.org/img/w/" + data.weather[0].icon + ".png" + ">";
console.log(data);
(function() {
$.getJSON("http://api.geonames.org/timezoneJSON?" + "lat=" + data.coord.lat + "&" + "lng=" + data.coord.lon + "&username=hrrs", function(data) {
document.getElementById("time").innerHTML = data.time;
document.getElementById("timeCity").innerHTML = data.timezoneId;
document.getElementById("country").innerHTML = data.countryName;
document.getElementById("sunrise").innerHTML = data.sunrise;
document.getElementById("sunset").innerHTML = data.sunset;
console.log(data);
});
})();
});
document.getElementById("slayt").innerHTML = '<iframe src="http://www.panoramio.com/wapi/template/slideshow.html?tag=' + d + '&width=1920&height=500&" frameborder="0" width="1920" height="500" scrolling="no" marginwidth="0" marginheight="0"></iframe>';
})();
});
});
Is this what you are trying to achieve?
http://jsfiddle.net/wnunhhac/
<input type="text" id="inputCity" value="Zurich"/>
<input type="button" id="start" value="Go" />
<br />
<span id="city">click go</span>
$(document).ready(function() {
$("#start").click(function() {
var d = $("#inputCity").val();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?APPID=11d324c05e02e308c1c9eb8d8041b143&q=' + d + '&units=metric', function(data) {
$("#city").html(data.name);
});
});
});
The API returns status code 404 not found, if the city is invalid. So you should code an appropriate resonse.
if (data.cod === "404") {
// Api could not find city
return;
}
Also I changed the button type to "button" instead of "submit"
<button type="button" id="button" class="btn btn-default">
Corresponding Fiddle: http://jsfiddle.net/xvn6f05w/

Generating Divs with unique buttons for toggling hide/show

Im making a contacts book, and with each new entry it generates a Div with all the information inside. I have gotten as far as giving each generated div a unique ID, and each button generated with the Div a unique ID, however I am having trouble associating the buttons with the div and allowing it to perform functions (such as toggling the visibility of the div).
Any help you can give is greatly appreciated, as I will soon be bald from frustration.
Updated Code with suggestions
The code that generates the DIV and Button:
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
The entire code
var surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ; //Declaring variables for the fields
var Contact = function(surname,firstName,date, phone , address , post, email, group){
this.surname = surname ;
this.firstName = firstName ;
this.birthdayDate = new Date (date) ;
this.phone = phone;
this.address= address;
this.email = email;
this.post = post;
this.group = group;
this.selected = false ;
}
var contacts = [];
divid = 0;
buttonid = 1000;
myControls = [];
var getDate = function() {
for (var i= 0, j=contacts.length;i<j;i++){
var y = contacts[i].birthdayDate.getFullYear();
var m = contacts[i].birthdayDate.getMonth();
var d = contacts[i].birthdayDate.getDate();
contacts[i].days = d;
contacts[i].months = m + 1;
contacts[i].years = y ;
var today = new Date() ;
var ty = today.getFullYear();
contacts[i].bdThisYear = new Date(ty,m,d, 0 , 0 , 0);
}
}
var daysUntilBirthday = function(){
for (var i= 0, j=contacts.length;i<j;i++){
var today = new Date() ;
contacts[i].daysUntil = Math.round((contacts[i].bdThisYear - today ) /1000/60/60/24+1);
if (contacts[i].daysUntil <= 0){
contacts[i].daysUntil = contacts[i].daysUntil + 365 ;
}
}
}
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
myControls.push(control);
var childDiv =
"<div style='border-style:double;border-width:6px;background-color: #2f4f4f;margin-left:auto;max-width: 700px;margin-right: auto;text-shadow:-1px -1px 1mm #000,1px -1px 1mm #000,-1px 1px 1mm #000,1px 1px 1mm #000;'>" +
this.firstName + " " + this.surname + "<button class='btnForDiv' style='color: black;' id='" + buttonid + "'" + "> Button </button>" +
"<div id='" + divid + "' " + "style='margin-right: auto;margin-left :40px;width: 300px;border-right-style: double;border-right-width:3px;'>" +
"<br>" + "Surname: " + this.surname + "<BR>" + "First Name:" + this.firstName + "<br>" +
"Date Of Birth: " + this.days + "/" + this.months + "/" + this.years + "/" + "<br>" + "Telephone Number: " + this.phone +
"<br>" + "Address: " + this.address + " " + this.post + "<br>" + "Email Address: " + this.email + "<br>" + "Group: " + this.group +
"<br>" + "Days Until Birthday: " + this.daysUntil + "<BR>" + "</div>" + "</div>"
return childDiv ;
}
var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
if(surnameField.value){
a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
contacts.push(a);
}else{ alert("Please complete all fields")}
}
var clearUI = function(){
var white = "#fff";
surnameField.value = "";
surnameField.style.backgroundColor = white;
firstNameField.value = "";
firstNameField.style.backgroundColor = white;
birthdayField.value="";
birthdayField.style.backgroundColor = white;
phoneField.value = "";
phoneField.style.backgroundcolor = white;
addressField.value = "";
addressField.style.backgroundcolor = white;
postField.value = "";
postField.style.backgroundcolor = white;
emailField.value = "";
emailField.style.backgroundcolor = white;
groupField.value="";
groupField.style.backgroundcolor = white;
}
var updateList = function(){
divid = 0;
buttonid = 1000;
myControls = []
var tableDiv = document.getElementById("parentDiv"),
cDiv = "<BR>" + "<div align='center'> Click a contact to expand</div>" ;
for (var i= 0, j=contacts.length;i<j;i++){
var cntct = contacts[i];
cDiv += cntct.generateDiv();
}
tableDiv.innerHTML = cDiv;
getDate();
daysUntilBirthday();
saveContacts();
}
var add = function(){
;
addContact(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField);
clearUI();
daysUntilBirthday();
getDate();
updateList();
};
var saveContacts = function(){
var cntcts = JSON.stringify(contacts);
if (cntcts !==""){
localStorage.contacts = cntcts;
}else{
alert("Could not save contacts");
}
}
var loadContacts = function(){
var cntcts = "";
if(localStorage.contacts !== undefined){
cntcts = localStorage.contacts;
contacts = JSON.parse(cntcts);
var proto = new Contact();
for (var i=0; i<contacts.length; i++){
var cntct = contacts[i]
cntct.__proto__ = proto;
cntct.birthdayDate = new Date(cntct.birthdayDate);
}
}
}
var clearContacts = function(){
contacts = [];
updateList();
}
//var periodUpdate = function(){
// setInterval(updateList, 10000);
//}
window.onload = function(){
loadContacts();
updateList();
surnameField = document.getElementById("surname");
firstNameField = document.getElementById("firstName")
birthdayField = document.getElementById("birthday");
phoneField = document.getElementById("phone");
addressField = document.getElementById("address");
postField = document.getElementById("post");
emailField = document.getElementById("email");
groupField = document.getElementById("group");
addButton = document.getElementById("addButton");
addButton.onclick = add;
delButton = document.getElementById("delButton");
delButton.onclick = clearContacts;
clearUI();
// periodUpdate();
}
The HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="contacts.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery-1.8.3.min.js">
$(document).ready(function(){
(".btnForDiv").on("click", function(){
// get the ID of the button
var id = $(this).prop("id");
var divid;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divid = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divid).toggle();
});
});
</script>
<div><title>Contacts Book</title></div>
</head>
<body>
<div class="information">
<heading><h1>Contacts Book</h1></heading>
</div>
<p><div class="information">Enter the contacts details below and click Add or select to view an existing contact.</div></p>
<hr>
<div class="entrydiv">
<table class="entryforms">
<br>
<tr>
<td>Surname</td><td><input type="text" class="inputboxes" id="surname" /></td>
</tr>
<tr>
<td>First Name</td><td><input type="text" class="inputboxes" id="firstName" /></td>
</tr>
<tr>
<td>Birthday</td><td><input type="date" class="inputboxes" id="birthday" /></td>
</tr>
<tr>
<td>Phone Number</td><td><input type="text" class="inputboxes" id="phone"></textarea></td>
</tr>
<tr>
<td>Email Address</td><td><input type="text" class="inputboxes" id="email" /></td>
</tr>
<tr>
<td>Address</td><td><input type="text" class="inputboxes" id="address"/></td>
</tr>
<tr>
<td>Postcode</td><td><input type="text" class="inputboxes" id="post" /></td>
</tr>
<tr>
<td>Group</td><td><select class="inputboxes" id="group"/>
<option value="Business">Business</option>
<option value="Educational">Educational</option>
<option value="Friend">Friend</option>
</td>
</tr>
</table>
<br>
<button id="addButton">Add Contact</button>
<button id="delButton">Delete Contacts</button>
</div>
<hr>
<div class="tablediv">
<h2 class="information" align="center">Contacts</h2>
<div id="parentDiv"></div>
</div>
</body>
</html>
The Solution
First of all massive thanks to Darren for his advice, which turns out to be spot on (with minor change)
First error I made was inserting jquery, I had
<script src="jquery-1.8.3.min.js">
//code
</script>
When I needed
<script src="jquery-1.8.3.min.js"></script>
<script>
//code
</script>
So that very minor mistake held me back for a while.
Secondly I used:
$(document).on('click','.btnForDiv',function(){
To call the Onclick event for my btnForDiv class buttons and the rest was all Darren :)
Thanks again
You could do a few things here.
One idea would be to store your generated div and button ID's in an array. You can then search this array for a given button ID to find its corresponding div.
For example (not tested...)
// outside your generatedDiv method
var myControls = new Array();
// then inside your generatedDiv method
var control = new Array();
control[0] = divId;
control[1] = buttonId;
myControls.push(control);
When you click your button you can grab its ID then search through the myControls array and look for the corresponding div
you could do a single function in jQuery to handle all the click for all of your generated buttons.
again (not tested) - give all your buttons a class, for example btnForDiv
$(document).ready(function(){
$(".btnForDiv").click(function(){
// get the ID of the button
var id = $(this).prop("id");
var divId;
// now find the div Id related to this button
for (var i = 0, len = myControls.length; i < len; i++){
if (myControls[i][1] == id){
divId = myControls[i][0];
break;
}
}
// you now have the div,so toggle it.
$("#" + divId).toggle();
});
});
I'm not 100% sure what your question was, though took a stab in the dark to help..
UPDATE
Because your div's are generated and added to the DOM dynamically you may have to use on instead of click - this will bind the click event to dynamic elements.
So try this:
$(".btnForDiv").on("click", function(){
// get the id.... etc...
});
also, make sure you did add the class btnForDiv to your dynamically generated buttons
this.firstName + " " + this.surname + "<button style='color: black;' id='" + buttonid + "b'" + " class='btnForDiv'> Button </button>" +

Categories

Resources