jquery .load() function multiple time - javascript

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
});
}

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()

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 Javascript toggle ID of div generated on runtime

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")
});

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.

Show/Hide Content without reloading the page

I have three content boxes that i want to show and hide using controls.
The HTML is as follows:
<div id="leermat1">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
<div id="leermat2">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
<div id="leermat3">
Content here
<a class="pag-next">Next</a>
<a class="pag-prev">Previous</a>
</div>
I have the two anchors pag-next and pag-prev that will control which of the content divs should be visible at any given point:
I want to write jquery such as, when #leermat1 'pag-next' is clicked, it hides #leermat1 and shows #leermat2. Then when #leermat1 is hidden and #leermat2 shows, when '.pag-next' is clicked, it hides #leermat2, and shows #leermat3.
Also the 'pag-prev' should work the same way.
I started with the following but dont know where to go from here.
$(document).ready(function() {
$('.pag-next').on('click',function() {
$('#leermat1').addClass('hide');
$('#leermat2').addClass('show');
});
});
One more thing is that the '.pag-next' should stop functioning after it has shown #leermat3.
You need this
$('[class^=pag-]').click(function() {
var elem = $('[id^=leermat]').filter(":visible"); // take the visible element
var num = Number(elem[0].id.match(/\d+$/)[0]); // take the number from it
var step = $(this).is('.pag-next') ? 1 : -1; // ternary operator
$('#leermat'+ (num + step)).show(); // show next or back
elem.hide(); // hide the visible element
});
Looks like in your anchor tag you have not given it a class.
Next
You then go on in your JQuery code to add a click function to a class which does not exist.
$('.pag-next').on('click',function()
Try adding class="pag-next" to your anchor tag.
This is what worked for me through a little trial and error. Although I am not sure if this is the most efficient solution.
$('#leermat1 .pag-next').on('click',function(){
$('#leermat1').addClass('hide');
$('#leermat1').removeClass('show');
$('#leermat3').addClass('hide');
$('#leermat3').remove('show');
$('#leermat2').addClass('show');
});
$('#leermat2 .pag-next').on('click',function(){
$('#leermat1').removeClass('show');
$('#leermat2').addClass('hide');
$('#leermat2').removeClass('show');
$('#leermat3').addClass('show');
});
$('#leermat2 .pag-prev').on('click',function(){
$('#leermat2').addClass('hide');
$('#leermat2').removeClass('show');
$('#leermat1').addClass('show');
$('#leermat3').removeClass('show');
});
$('#leermat3 .pag-prev').on('click',function(){
$('#leermat3').addClass('hide');
$('#leermat2').addClass('show');
$('#leermat1').addClass('hide');
$('#leermat3').removeClass('show');
$('#leermat1').removeClass('show');
});

Categories

Resources