javascript that can access element declared in a variable - javascript

List item
i want a javascript that can access the button elements inside
the
dot.append() function. so that when i clicked the button i
get the value of that button.
below is a piece of code that have been working on this morning.
i appreciate any support or hint from anyone.Thank you in
advance.
further more i am also new in youtube data api.
function main_search(){
$("form").on("submit",function(e){
e.preventDefault();
//after that we prepare the request
var myRequest = gapi.client.youtube.search.list({
part: 'snippet',
q: encodeURIComponent($("#query").val()).replace(/%20/g, "+"),
maxResults :5,
type : 'video'
});
// then we execute the request
myRequest.execute(function(response){
var results = response.result;
$.each(results.items, function(index,item){
$("#results").append('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
});
});
});
}
function loadAPI(){
gapi.client.setApiKey("AIzaSyC1CJHONRDvyfSS3xAOG9SfW_VCXMoLK5Y");
gapi.client.load("youtube","v3", function(){
//my youtube api is read
main_search();
});
}
<form action="#">
<input type="search" id="search_string" placeholder="Your string
goes
here...."></input>
<input type="submit" name="search-btn" id="search_btn" value="search">
</input>
</form>
<ul id="result_box"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script src="search.js"></script>

Just divide your statement into two lines so that you can access the element later:
var element = document.createElement('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
$("#results").append(element);
Or if you want a jQuery object instead:
var element = $('<li>'+item.id.videoId+" "+item.snippet.title+"
"+item.snippet.channelTitle+" "+item.snippet.description+"
"+item.snippet.publishedAt+" "+'<img
src="'+item.snippet.thumbnails.high.url+'">'+'<button
class="class_btns" value="'+item.id.videoId+'">'+'get video url
'+'</buttons>'+'</li>'+"<br>");
You can then access whatever you want from the element variable.
Alternatively you can just grab the button later using the class if you keep your current code:
var button = $('.class_btns');

Related

Sending data and saving in a text field

I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer

how to transfer values between html pages?

I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code&parameter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).

Javascript display form results in iframe

I have simple form on my webpage that passes search variables to an external page. The functionality is working as expected, I'd like to change how/where the results are displayed.
I'd like to display the search results on the same page as the search box, i.e I don't want a new window or tab to open. Ideally I would like to display the results in a hidden <div> and stay away from iframes altogether, however I don't think that's possible?
Both pages (search and results) are on the same domain, however I only have access to edit the search page code.
What do I need to change in my current code in order to get this working. I'm open to suggestions if there's a better way to do this, such as using AJAX etc. Pretty new to JS so all help is much appreciated.
The results page URL is in the following format upon a successful search of the word 'sport';
http://example.com//search/C__Ssport__Orightresult__U
My code so far is as follows;
HTML
<form action="" onsubmit="return search()">
<input id="SearchInput" placeholder=" Search..." type="text">
<input type="hidden" id="Base" value="http://example.com/search/">
<input type="submit" value="Submit">
</form>
JS
<script type="text/javascript">
function search(){
var BaseURLInput, BaseURL, searchInput, searchString, locationHref, charRegExString, base64Regex;
var base64_encoding_map = {"=":"PQ==", "/": "Lw==", "\\":"XA==", "?":"Pw=="};
var escapeRegExp = function(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
BaseURLInput = document.getElementById("Base");
searchInput = document.getElementById("SearchInput");
if (searchInput && BaseURLInput) {
BaseURL= BaseURLInput.value;
searchString = searchInput.value;
for (var specialChar in base64_encoding_map) {
charRegExString = escapeRegExp(specialChar);
base64Regex = new RegExp(charRegExString, "g");
searchString = searchString.replace(base64Regex, base64_encoding_map[specialChar])
}
searchString = encodeURIComponent(searchString);
locationHref = BaseURL+ "C__S" + searchString + "__Orightresult__U";
window.open(locationHref,'_blank' );
}
return false;
}
</script>
Instead of opening results page you could make an AJAX call.
In this answer you have a good example of how to do them:
How to make an AJAX call without jQuery?
The idea is to call the results page with an AJAX call and directly embed the results returned to you into your preferred html container.

Find and replace an element in html using jquery

I am trying to load a HTML page into a variable in Jquery, then replace a div element tag in it, so I can get my own id into the div. I am using this way to dynamically add more users in my web app, and then do a batch POST to the back end, and put the info into json.
Here is my html that I am loading.
info.html
<div id="user">
<label>name</label>
<input type="text" name="name">
<br>
<label>email</label>
<input type="text" name="email">
<br>
</div>
I load this with jquery and I want to replace <div id="user"> with something
like <div id="user 1">
I have the following jquery script that has a counter to keep track of what number to append onto the div tag.
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
var content = $('<div>').load("static/info.html"); //using python flask
console.log(typeof(content)); //is of object type
console.log(typeof(content.html())); //is of type string
console.log(content.html());//shows up as an empty string
console.log(content);//prints out the object
content = content.html().replace('<div id="user ">','<div id="user "'+counter+'>'); // doesn't work.
$("#add_div").append(content); //appends correctly if I remove the above line, but all divs have the some id.
});
});
Any suggestions would be great thanks. Also, is the is the best way going about keeping track of how many times a new user is added(as in using a counter and keep track of how they are added, and then do the same when I click submit and create the json)?
.load() is asynchronous. make your changes in side callback.
.load("..",function(){
// your changes
});
Also $( "selector" ).load() is the syntax. So create a div and load content to it.
// modified code structure
<div id"content"></div>
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
$("#content").load("static/info.html",function(){
content = $("#content").html().replace('<div id="user ">','<div id="user "'+counter+'>');
$("#add_div").append(content);
}); //using python flask
});
});
Using JavaScript, you can use the .attr() method to target id, then set its value like so:
$("#content").attr("id", "user_" + counter);
Try an $.each() function for #user like this:
$('#user').each(function(indexNumber){
$(this).replace('<div id="user'+indexNumber+'"></div>');
});

Passing element in XMLHttpRequest to one function but second one also knows, why?

I am working on the jsp/servlet/ajax application.
I use XMLHttpRequest to pass values from the JSP page to servlet, which retrieve data from the database and returns XML to the JSP.
The code works but there is one thing I do not understand.
Here is a JSP part
<body>
<label>Longitude</label><input type="text" id ="lat" value="40.799559" />
<br/>
<label>Latitude</label><input type="text" id="lon" value="-74.481386" />
<br/><br/>
<input type="button" onclick="checkGPSCoords(document)" value="Test" />
<br/><br/>
<input type="text" id ="dbCounty" readonly/>
<br/>
<input type="text" id ="dbMuni" readonly />
<br/><br/>
</body>
I am passing a document element into the JavaScript
Here is a script:
<script type="text/javascript" language="JavaScript">
var req;
var isIE;
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function checkGPSCoords(currentWindow){
var lat= currentWindow.getElementById("lat").value;
var lon = document.getElementById("lon").value;
//alert("lon:" + lon);
initRequest();
req.open("GET","./lonlat?lat="+ lat + "&lon=" + lon);
req.onreadystatechange = retrieveMuniCntyNames;
req.send(null);
}
function retrieveMuniCntyNames() {
var muniAndCnty;
if (req.readyState==4) {
if(req.status==200) {
var XMLresult = req.responseXML;
muniAndCnty = XMLresult.getElementsByTagName("rec");
//incoming from Servlet <twp><rec twp='Morristown town' cnty='Morris' /></twp>
var c = document.getElementById("dbCounty");
var t = document.getElementById("dbMuni")
c.setAttribute("value",muniAndCnty[0].getAttribute("cnty") )
t.setAttribute("value",muniAndCnty[0].getAttribute("municipality") )
}
}
}
</script>
Function checkGPSCoords knows a document name (which is my JSP file name).
What I puzzle me that callback function retrieveMuniCntyNames() also knows the name of the document since it sets attributes to input elements on the JSP without error.
I checked it the firebug.
I would appreciate any thoughts on the subject.
Thanks,
Chris
I'm unsure what setup you're trying to convey here, or where the javascript would be in the code. I'm making the assumption here that you've defined the script in the same page or you're including it from an external file.
Nonetheless, when the javascript executes, the browser isn't leaving the page. Therefore, the document doesn't change. From the code you've provided, you're not attempting to open a new window or navigate away from the page. Therefore the document variable hasn't changed from one function call to another, even after a successful AJAX call. It's the same document before, during, and after the AJAX call.
By that same token, you can probably eliminate the currentWindow parameter from your checkGPSCoords function. You're not really checking a window object since you're passing a document object to the function. Also, the window object doesn't have a getElementById method.

Categories