I have several content items on the page all of the are hidden and they have each a unique ID. #data serves as a temporary stack.
<div id="data"></div>
<div id="item1212">...</div>
<div id="item2323">...</div>
<div id="item3434">...</div>
<div id="item4545">...</div>
an Ajaxrequest gives me back a certain ID
$('#data').load('http://someURL');
fills the #data:
<div id="data">2323</div>
width this lines I make my correspondig item visible:
var theID = $('#data').text().val();
$('#item'+theID).toggleClass('visible');
This was my idea. Guess: Ist does not work cause it fails to read #data and use the value as a string. Its alwas an object (?).
I save the value first in html cause I dont know how to save a ajax-result (its always a string value) to a JS variable.
But I guess you have much better ideas how to solve my Problem: Show item width an certain ID that is receved by ajax
Your logic works fine (aside from the fact you don't need val()), you just need to execute it after the load() call completes as it is asynchronous. Currently you're trying to access the new content before it exists. To do that you can use the callback parameter, like this:
$('#data').load('http://someURL', function() {
var theID = $('#data').text();
$('#item' + theID).toggleClass('visible');
});
Related
When i call data/listing.json directly it works fine.
<div data-endfavpoint="data/listing.json" data-expiring-days="3" data-new-days="7" data-brand="" data-property="" data-hide="false" class="component">.....</div>
Issue here, i want to call Cookie array value parsed in JSON Format like below using JSON.parse. But, getting error because of JSON.parse($.cookie('offer')) code.
<div data-endfavpoint="JSON.parse($.cookie('offer'))" data-expiring-days="3" data-new-days="7" data-brand="" data-property="" data-hide="false" class="component">....</div>
Please let me know how to call JSON.parse($.cookie('offer')) inside data attribute and display values inside div.
I would set attribute in a script, since you use jquery:
<script>
$(document).ready(function(){
$(".component").attr("data-endfavpoint", $.cookie("offer"));
});
</script>
Alrighty, so I am trying to make a little page on my website that takes a few values and then when you click a button, it adds those values inside of a div on a different HTML page.
My code is:
<input type="text" name="URL"><br>
<input type="text" name="ImageURL"><br>
<input type="text" name="Title">
<button onclick="addCode()">Submit</button>
So for the addCode() function I want it so that it adds the values inside of a the item div on a different HTML file just like:
<div class="item">
<div class="animate-box">
<a href=URL><img src=ImageURL></a>
<div class="fh5co-desc"><a style="TEXT-DECORATION:none; COLOR:#818892; LINE-HEIGHT:20px;" href=URL>Title</a></div>
</div>
</div>
Thanks in advance.
What you are doing is technically impossible. without some sort of persistence, that is;
you cannot edit a page you aren't on. web browsing is a stateless technology.
if you meant you want to fill out those inputs then redirect on click and have those values available, there are a few different ways to do it:
1) Query String
write your code on the second page in a way that it accepts params from a query string in the url bar
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var textDecoration = getUrlParameter('textdec'),
color = getUrlParameter('color'),
lineHeight = getUrlParameter('lnheight');
then you can send the request for the page as
http://page.com/page?textdec="someval"&color="somecolor"&lnheight="someheight"
however this will not work if you are not going directly to that page after your current one
2) localStorage
on your first page set the local storage values:
localStorage.setItem('lineHeight', 'someVal');
localStorage.setItem('color', 'someColor');
localStorage.setItem('textDecoration', 'someVal');
then on your second page retrieve the values
var lineHeight = localStorage.getItem('lineHeight'),
color = localStorage.getItem('color'),
textDecoration = localStorage.getItem('textDecoration');
3) serverSide persistence
this will vary MASSIVELY depending on how you your backend is structured
but the general gist is make a post request (ajax or otherwise) &
collect the data on the backend
then when you render the second page send the variables that were posted, either through interpolation or included as script variables
The only way to do this (without getting other technologies involved) is to use the localStorage, storage event. And, even with this, it will only work when the two pages are coming from the same domain and are open in different browser tabs (of the same browser) at the same time.
If those conditions are present, then modifying localStorage on one page will fire the storage event, which the other page can be set up to listen for. The other page can then respond to the event by pulling new values (that the first page wrote into localStorage) out and placing them anywhere on the second page that you like.
This is the kind of solution that you might encounter if you were on a travel site with more than one browser tab open. You may be looking at different flight options in different tabs. If one tab's code has an update that any/all other open tabs should know about, this technique does the trick.
Here's an example of how to set values into localStorage and use them. But, localStorage doesn't work here in the Stack Overflow snippet environment, so you can run the code here.
Once the values are in localStorage, you can pick them up from any other page that is being served from the same domain. So, the "getItem" code I'm showing here would really be placed on your "page2.html".
// Get DOM references:
var name = document.getElementById("name");
var color = document.getElementById("color");
var airspeed = document.getElementById("airspeed");
var btn = document.getElementById("btnGo");
// Set up button click event handler:
btn.addEventListener("click", function(){
// Get values and place in localStorage
localStorage.setItem("name", name.value);
localStorage.setItem("color", color.value);
localStorage.setItem("airspeed", airspeed.value);
// For demonstration, get values out of localStorage
console.log("What is your name? ", localStorage.getItem("name"));
console.log("What is your favorite color? ", localStorage.getItem("color"));
console.log("What is the airspeed of a laiden swallow? ", localStorage.getItem("airspeed"));
// If you wanted to redirect the user to the second page, now that the intial values
// have been set, you could just do:
location.href = "path to second page";
});
<div>What is your name?<input type="text" id="name"></div>
<div>What is your favorite color?<input type="text" id="color"></div>
<div>What is the airspeed of a laiden swallow?<input type="text" id="airspeed"></div>
<button id="btnGo">Go!</button>
If you're trying to edit the actual source code of the file, you'll need something like PHP. Otherwise, JS is just fine.
PHP Solution
You could use something like this:
<?php
$old = file_get_contents("some_page.html");
$content = explode("<span>",$old,2); // replace <span> w/ opening tag
$content = explode("</span>",$content[1],2); // replace </span> w/ closing tag
$data = "new content of element";
$new = str_replace($content[0],$data,$old);
?>
Updated JS Solution
You can't use my previous solution. Instead, you would have to create a function in the second HTML file that could be called from the first file, like this:
A script in file2.html:
function set(id,val){
$("#"+id).html(val); // jQuery
document.getElementById(id).innerHTML = val; // pure JS
}
A script in file1.html:
var win = window.open("http://example.com"); // open the window
win.set("some_id","Some content.") // the function that we set earlier
Note that this is reverted once the user closes or reloads the tab, and only applies to that user and that tab.
I am developing a registry system for my school/workplace, and the instructors need a thorough list of the students who fall into 5 separate categories:
Have not met and have not registered absence
Have not met but registered absence after 8 am
Have not met but registered absence before 8 am
Have met but registered reason for absence after 8 am
Have met and registered before 8 am
As the first one (Have not met and not registered) will be loading student data across 3 databases for checkup, getting the data might take some time. I figured instead of loading all the data through PHP, displaying a white screen to the user until everything is loaded, instead I would load the page and then get the data using JQuery AJAX functions.
The AJAX loading and displaying works using this code:
//Not met and not registered
div1 = $("#not-met-not-registered");
div1.find(".text").html("<img src='' class='loader'>");
$.post("/admin_post/getusers", {area:"not-met-not-registered"}, function(data) {
div1.find(".text").html(data);
div1.find("tr").each(function (row) {
datatable1.push({
"Row": $(this),
"Navn": $(this).find("td.navn").html()
});
});
});
However, this only works as I staticly input the div value, and save the div value in 5 different names (div1, div2 etc.).
To receive the data, I have 5 divs looking like this:
<div id="not-met-not-registered" class="list">
<label>Students who have not met and not registered absence</label>
<img src="/images/search.png" class="search">
<input type="text" class="search">
<div class="text"></div>
<input type="button" value="Print">
</div>
Each div has the unique id that AJAX should send via POST to get the liable data. Which is why I figured something along the lines of this would be applicable:
$("div.lists div.list").each(function() {
$(this).on("ready", {div: this}, function (eventObject) {
div = eventObject.data.div;
$.post("/admin_post/getusers", {area: $(div).attr("id")}, function (data) {
div.find("div.text").html(data);
div.find("tr").each(function (row) {
datatable.push({
"Row": $(this),
"Name": $(this).find("td.name").html()
});
});
});
});
});
The function would save the div in question inside the eventObject.data array, and use the id of that div as search criteria on the PHP page. By saving the div as a value in the eventObject, I would be able to use the same name other places I figured, since, as seen below, that idea worked for my search function using eventhandlers.
Each table is given their own search opportunity using a functional eventhandling code, though not yet built for the full purpose:
$(this).find("input[type=text].search").on("change", {preVal: ""}, function (eventObject) {
preVal = eventObject.data.preVal;
curVal = $(this).val();
if (preVal != curVal) {
eventObject.data.preVal = curVal;
alert(curVal);
}
});
I am aware that I am not a very skilled JS or JQuery coder, and perhaps I am going way out of best practice or missing something very obvious. I really hope you can help me out anyway though!
I managed to find out what the fault was, and figure I would post it here.
So, for some reason, when you call a function in JQuery and save a variable in it, the next time you call the same function and save a new value in the variable, the new variable is saved in the old function call.
Right now I save the element e in div
div = e;
When I call it 5 times:
div = 1
div = 2
div = 3
div = 4
div = 5
Then, when the AJAX returns, what it sees is this:
div = 5
div = 5
...
By removing the div part of it, I made it work:
function load_in(e, link, target, data)
{
$.post(link, {data:data}, function(data) {
$(e).find(target).html(data);
enable(e);
setCount(e);
});
}
This function takes the e-lement, the link you AJAX to, the Target that you want your result to go into and whatever data you wish to send as POST data
Callable with this:
load_in(this, "/admin_post/getusers", "div.list", $(this).attr("id"));
I am requesting a full page using $.get in jQuery and would like to get the content of a specific element. Separately, here is how things look:
$.get( "/page.html").done(function( data ) {
// get textArea.
});
and I want to get:
document.getElementByTagName("textArea")[0].value;
but I can't do getElementByTagName on data so what is the best way to do this?
I tried using find but that did not work so I ended up using filter and that returned the value of textArea that I needed:
$.get( "/page.html").done(function( data ) {
var textArea = $(data).filter("textarea")[0].innerText;
});
It's slightly different of what you are doing but i think it can help. You can call .load instead of get and add the whole page to a div say <div id="mydiv"></div>
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()})
however if you do not want mydiv to show you can hide at the beginning once the main page gets loaded and if you also don't want this div on your page you can remove it after the above task is performed.
$(document).ready(function(){
$('#mydiv').hide();
var value;
$('#mydiv').load('xyz.html',function(){value=$('#mydiv').find('#mytextarea').val()});
$('#mydiv').remove();
})
//str represents page.html
var str = 'gibberish gibberish <textarea class="test">hello world</textarea>gibberish';
$.each( $.parseHTML(str), function( i, el ) {
if(el.firstChild) console.log(el.firstChild);
});
Fiddle: http://jsfiddle.net/ez666/7DKDk/
You could try jquery load() function.
It will load from remote server and insert document into selected element.
It also allow us to specify a portion of remote document to be inserted.
Assume your remote textarea's id is "remote" and you want to fetch the remote content into a textarea which id is "local"
var result="";
$("#local").load("/page.html #remote", function(response, status, xhr){
result=$(this).find("#remote").val();
});
I'm not sure if you want to get the remote textarea and insert into the element of the current document.
If you just want to get the value of the remote textarea, you could just hide the load function invoking element
Hope this is helpful for you.
Since you're using jQuery anyway… have you tried $(data).find('textarea').first().val() yet?
This is assuming that data is a fragment. If it is not you will want to wrap it in a div or something first.
$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?
Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});
this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));
post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});