how to Javascript toggle ID of div generated on runtime - javascript

I am sending a Model to a View in MVC,
and for each "Person" in my Model, I want to create a button that says "Show Details", when the user clicks it, a div with more information about that person toggles.
I am generating a a href and div id assigned to each person ID like the following:
foreach (var person in Model.Persons)
{
<div>
Show Details
</div>
<div id="#Html.Raw("detailsDiv-" + #person.id)">
<!--Content Here -->
</div>
}
I want to create the javascript that toggles on a click event
So I want to write this script but with the unique id for each person:
I want to get the id of the div that needs to be toggled.
I tried writing the script inside the foreach loop so I can be able to read the #person.id value, but it didnt work:
<script>
$(document).ready(function () {
$("#showDetails-#person.id").click(function () {
$("#details-#person.id").toggle();
});
});
</script>
Can anyone help?

put a class to your links like class="showDetails".
Now you Can create a global Event for all that links:
$('.showDetails').click(function(e) {
var id = this.id // extract id.. split with '-' or whatever..
$('#details-' + id).toggle();
});

you could put the id in a tag like "person_id" and use a class to trigger the jquery event.
<div class="middle_right">
<a class="showDetails" href="#" person_id="#Html.Raw("showDetails-" + #person.id)">Show Details</a>
</div>
and in js
$(".showDetails").click(function () {
var person_id=$(this).attr("person_id")
});

Related

slide hidden div on an onclick event

I have the following php while loop code:
while (...($...)){
$convid = $row['ID'];
echo"
<button onclick='getconvo($convid)'>open</button>
<div class="convowrap"></div>
";
}
and the javascript code
<script type='text/javascript'>
$(document).ready(function(){
$(".convowrap").hide(0)
})
</script>
script type='text/javascript'>
function getconvo(id){
$(".convowrap").hide(0).delay(200).slideDown(500)
var convid = id;
$('.convowrap').load('fetch_info.php', {id : convid}, function () {
// do something when success
});
}
</script>
When i click on the button above that says 'open,' all of the div that says convowrap slides, but i only want the current div to slide based on the button that was clicked that was generated from the php while loop.
If the php loop executed three times, when i click on the first button generated by the first loop, the convowrap div slides on all three entries generated by the loop.
What do I do? Please help?
Thanks in advance.
The problem is that all the divs have the same class so its functioning as you it is supposed to ...
As you have the div after the button you can replace
$(".convowrap")
With
$(this).next()
Inside the function for both .load and .hide
(Whichever you want)
more generic
It may be more usefull to assign another class to each div like
<div class='convowrap dummyclass$convid'></div>
And on button click change the selector to match that class like
$('dummyclass'+id)
Hope this helps
As you are using inline onlclick function inside HTML, you have to pass this explicitly like onclick='getconvo(this)'.
Anyway, see the following fiddle and hope you wanted this workaround -
https://jsfiddle.net/nuhil/4scas2gh/
Code:
<button onclick='getconvo(this)' id="1">Button 1</button>
<div class="convowrap">Content First</div>
<br/>
<button onclick='getconvo(this)' id="2">Button 2</button>
<div class="convowrap">Content Second</div>
<!-- More pairs of (button and div) go here -->
<script>
$(document).ready(function(){
$(".convowrap").hide();
})
function getconvo(button){
$(button).next().delay(200).slideDown(500);
// You could use toggle here like following for better UX
// $(button).next().toggle("slow");
// Anyway,
// Get the id from button attribute but make sure you already set it by PHP
var convid = $(button).attr("id");
console.log(convid);
// $(button).next().load('fetch_info.php', {id : convid}, function () {
// do something when success
// });
}
</script>

how to recode my jquery/javascript function to be more generic and not require unique identifiers?

I've created a function that works great but it causes me to have a lot more messy html code where I have to initialize it. I would like to see if I can make it more generic where when an object is clicked, the javascript/jquery grabs the href and executes the rest of the function without the need for a unique ID on each object that's clicked.
code that works currently:
<script type="text/javascript">
function linkPrepend(element){
var divelement = document.getElementById(element);
var href=$(divelement).attr('href');
$.get(href,function (hdisplayed) {
$("#content").empty()
.prepend(hdisplayed);
});
}
</script>
html:
<button id="test1" href="page1.html" onclick="linkPrepend('test1')">testButton1</button>
<button id="test2" href="page2.html" onclick="linkPrepend('test2')">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
I'd like to end up having html that looks something like this:
<button href="page1.html" onclick="linkPrepend()">testButton1</button>
<button href="page2.html" onclick="linkPrepend()">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
If there is even a simpler way of doing it please do tell. Maybe there could be a more generic way where the javascript/jquery is using an event handler and listening for a click request? Then I wouldn't even need a onclick html markup?
I would prefer if we could use pure jquery if possible.
I would suggest setting up the click event in JavaScript (during onload or onready) instead of in your markup. Put a common class on the buttons you want to apply this click event to. For example:
<button class="prepend-btn" href="page2.html">testButton1</button>
<script>
$(document).ready(function() {
//Specify click event handler for every element containing the ".prepend-btn" class
$(".prepend-btn").click(function() {
var href = $(this).attr('href'); //this references the element that was clicked
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
</script>
You can pass this instead of an ID.
<button data-href="page2.html" onclick="linkPrepend(this)">testButton1</button>
and then use
function linkPrepend(element) {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
NOTE: You might have noticed that I changed href to data-href. This is because href is an invalid attribute for button so you should be using the HTML 5 data-* attributes.
But if you are using jQuery you should leave aside inline click handlers and use the jQuery handlers
<button data-href="page2.html">testButton1</button>
$(function () {
$('#someparent button').click(function () {
var href = $(this).data('href');
$.get(href, function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
});
});
$('#someparent button') here you can use CSS selectors to find the right buttons, or you can append an extra class to them.
href is not a valid attribute for the button element. You can instead use the data attribute to store custom properties. Your markup could then look like this
<button data-href="page1.html">Test Button 1</button>
<button data-href="page2.html">Test Button 1</button>
<div id="content">
</div>
From there you can use the Has Attribute selector to get all the buttons that have the data-href attribute. jQuery has a function called .load() that will get content and load it into a target for you. So your script will look like
$('button[data-href]').on('click',function(){
$('#content').load($(this).data('href'));
});
looking over the other responses this kinda combines them.
<button data-href="page2.html" class="show">testButton1</button>
<li data-href="page1.html" class="show"></li>
class gives you ability to put this specific javascript function on whatever you choose.
$(".show").click( function(){
var href = $(this).attr("data-href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
This is easily accomplished with some jQuery:
$("button.prepend").click( function(){
var href = $(this).attr("href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
And small HTML modifications (adding prepend class):
<button href="page1.html" class="prepend">testButton1</button>
<button href="page2.html" class="prepend">testButton2</button>
<div id="content"></div>
HTML code
<button href="page1.html" class="showContent">testButton1</button>
<button href="page2.html"class="showContent">testButton1</button>
<!-- when clicking the button, it fills the div 'content' with the URL's html -->
<div id="content"></div>
JS code
<script type="text/javascript">
$('.showContent').click(function(){
var $this = $(this),
$href = $this.attr('href');
$.get($href,function (hdisplayed) {
$("#content").empty().prepend(hdisplayed);
});
}
});
</script>
Hope it helps.

Jquery: how to know which element was clicked?

I have an html code with 5 divs. They all have the same class, and different IDs.
Then, within javascript I have this:
$(".pics").click(function() {
alert("hey!");
});
where .pics is the name of the class of all the divs. The idea is that when I click on any of them, a certain script should be triggered, but I also want to know which one of the divs was clicked upon.
How do you go about it?
Thanks.
Assuming your ids are like this:
<div class="pics" id ="pic1">...</div>
<div class="pics" id ="pic2">...</div>
<div class="pics" id ="pic3">...</div>
<div class="pics" id ="pic4">...</div>
<div class="pics" id ="pic5">...</div>
Then in your javascript:
$(".pics").click(function() {
alert("You are clicking "+$(this).attr('id'));
});
And you should see something like this:
You are clicking pic1
Try this:
$(".pics").click(function() {
alert("hey!" + $(this).attr("id"));
});
You can get this information from the target of the click event, as shown here.
$(".pics").click( function (e) {
var clickedElement = e.target;
})
this refers to that element.
$(".pics").click(function() {
var me = $(this);
alert(this.id);
});

jquery .load() function multiple time

How do i load a test.html multiple time using jQuery.
function loadScreen()
{
$('#result').load('test.html');
}
main.html
<div id='result'></div>
<input type="button" value="click me" onclick="loadScreen()">
test.html
<body>
<p>
testing
</p>
</body>
Current situation
when i click the button click me. it will load once
show on main.html
testing
what i want to do
How can i do it when i click the button twice
it will show
testing
testing
and with different div id
1st time button click show testing <div id="result1">testing</div>
2nd time button click show testing <div id="result2">testing</div>
it will append incremental 1 at id.
load() will replace the content of the target element which is why it's not working as you want.
Try this instead:
function loadScreen() {
var divId = $("#result > div").length + 1;
$('#result').append("<div></div>").attr("id", "result" + divId).load('test.html');
}
Then it's about time you should use $.get(), then create a div via the $(), add in the contents using .html() and .appendTo() the results div.
var result = $('#result'), //cache result box
i = 0;
function loadScreen(){
$.get('test.html',function(data){ //initiate get
$('<div>',{ //create div for return data
id : 'result'+(++i) //add attributes
})
.html(data) //add data
.appendTo(result); //append to result
});
}

jQuery: How to assign the right ID to a button dynamically

I have a JS/jQuery script that adds our leads (web contacts) to the DOM in a for loop. Everything works fine except for one thing. I want the body of the lead to be hidden upon the initial display, and then have a slideToggle button to display or hide the details That means dynamically adding click events to each button as it is created. The entire HTML (HTML and a JSON object mixed into the HTML) of the lead and the slideToggle button are all appended to a node in the DOM in the for loop. Here is the pertinent part of the for loop:
// Hide the body of the lead; just show the title bar and the first line
var dataID = data[i].id
var div = $('#row' + dataID);
var more = $('#more' + dataID);
div.hide();
// Create click event for each "+" button
more.click(function() {
div.slideToggle();
});
But when I click on the "+" button to reveal the details, it opens the last div, not the div I am trying to open. This is true no matter how many leads I have on the page. How do I get the click event to open the right div. If I console.log "div" in the click event, it gives me the ID of the last div, not the one I am clicking on. But if I console.log(div) outside the click event, it has the right ID.
Also, I was unsure whether I needed the "vars" in the loop or if I should declare them outside the loop.
Here is the HTML. It's one lead plus the beginning of the next lead, which I left closed in Firebug
<div id="lead1115">
<div id="learnmore">
<a id="more1115" class="more" href="#">+</a>
</div>
<div id="lead-info">
<div id="leadID">Lead ID# Date: March 27, 2012 11:26 AM (Arizona time)</div>
<div id="company">No company given</div>
<div id="name">Meaghan Dee</div>
<div id="email">
meaghan.dee#gmail.com
</div>
<br class="clearall">
<div>
<div id="row1115" style="display: none;">
<div id="phone">No phone given</div>
<div id="source">www.ulsinc.com/misc/expert-contact/</div>
<div id="cp-name">No channel partner chosen</div>
<br class="clearall">
<div id="location">
No location given
<br>
<strong>IP Address:</strong>
198.82.10.87
<br>
<span>Approximate Location: Blacksburg, Virginia, United States</span>
<br>
</div>
<div id="details">
<strong>Questions/Comments</strong>
<br>
We have the Professional Series Universal Laser Systems (laser cutter), and I wondered how I would order a high power density 2.0 replacement lens.nnThank you
</div>
</div>
</div>
</div>
<div id="learnmore">
<a id="1115|send_message" class="verify" href="#">Verify</a>
<a id="1115|send_message" class="markAsSpam" href="#">Spam</a>
<a id="1115|send_message" class="markAsDuplicate" href="#">Duplicate</a>
</div>
</div>
<br class="clearall">
<div id="lead1116">
<br class="clearall">
Try using .bind (or .on for 1.7+) and the data parameter.
more.bind("click",{target:div},function(e){
e.data.target.show();
}
or
more.on("click",{target:div},function(e){
e.data.target.show();
}
I think your basic problem is that div is common as a variable to all items. You have to separate the div's from each other by, for example, creating a local function and call it for each item. Something like:
function buildMore(div) {
more.click(function() {
div.slideToggle();
});
}
and in the loop call:
addMore(div);
p.s.
Whether you declare your variables inside or outside the loop doesn't matter: you still get the same variables.
This is because div variable gets changed and settles with the last value set in the loop.
Try this:
...
funciton createClick(div) {
return function() { div.slidToggle();
}
more.click( createClick(div) );
...
The variable div doesn't stay frozen with your click handler so it's value will be what it was at the end of the for loop and all click handlers will use the same value (which is what you're seeing).
There are a number of different ways to approach this and I thought all would be educational. Any one of them should work.
Idea #1 - Manufacture the row id from the clicked on more id
Use the id value on the clicked on link to manufacture the matching row ID. Since you create them in pairs, this can be done programmatically like this:
// Hide the body of the lead; just show the title bar and the first line
var dataID = data[i].id
$('#row' + dataID).hide();
$('#more' + dataID).click(function() {
// manufacture the row ID value from the clicked on id
var id = this.id.replace("more", "#row");
$(id).slideToggle();
});
Idea #2 - Use a function closure to "freeze" the values you want
Another way to do that is to create a function and closure that will capture the current value of div:
// Hide the body of the lead; just show the title bar and the first line
var dataID = data[i].id
var div = $('#row' + dataID).hide();
var more = $('#more' + dataID);
function addClick(moreItem, divItem) {
// Create click event for each "+" button
moreItem.click(function() {
divItem.slideToggle();
});
}
addClick(more, div);
Idea #3 - Use the HTML spatial relationship to find the row associated with a more
To make this work, you need to put a common class=lead on the top level lead div like this:
<div id="lead1115" class="lead">
And, a common class on each row:
<div id="row1115" class="row" style="display: none;">
Then, you can use the position relationships to find the row object that is in the same parent lead object as the clicked on more link like this:
// Hide the body of the lead; just show the title bar and the first line
var dataID = data[i].id
$('#row' + dataID).hide();
$('#more' + dataID).click(function() {
// find out common parent, then find the row in that common parent
$(this).closest(".lead").find(".row").slideToggle();
});
Idea #4 - Put the row ID as data on the more link
// Hide the body of the lead; just show the title bar and the first line
var dataID = data[i].id
$('#row' + dataID).hide();
$('#more' + dataID).data("row", "#row" + dataID).click(function() {
// get the corresponding row from the data on the clicked link
var rowID = $(this).data("row");
$(rowID).slideToggle();
});

Categories

Resources