Javascript compare string in an array - php

function getPublicLink() {
var div = document.getElementById('links'); // anchor tag
var url;
for(var x in div){
url += div[x].href;
}
}
This is for getting the list. My Problem is that I want to compare it with the json results below. If there is a matched. I will alter the anchor tag to remove the href attribute or make the text Connected ( Now it is "Invited"). The Linkedin connection code is:
function displayConnections(connections) {
var members = connections.values;
var publicUrl;
for(var member in members) {
publicUrl += members[member].publicProfileUrl;
}
}
My problem is they are in a big string. What i want is to compare them one by one. I'm out of ideas since I'm just a JS beginner. Thanks for your input!

I've found the answer.
for(var i in publicUrl) {
for(var j in url) {
if(url[j] === publicUrl[i]) {
alert("Found " + url[j]);
}
}
}

Related

Get index value from dropdown form

I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>

Load the page content using jQuery?

Using jQuery load html forms dynamically using append function. Here the following code load the page content dynamically based on number times of values on while loop.
Here I have a struggle on load the content with different values.its working with single value of 0 or 1 on var load_with_value=0; but not on both simultaneously i.e. increment the load_with_value++ for again load the page content of HTML forms.
$(document).ready(function(e) {
$("<DIV>").load("<?php echo $url; ?>", function() //url for loading page
{
var n = $('.item').length + 1; //load the html page content
var i = 1; //iteration for number of times load the content
var count = 2; //check the condition
var load_with_value = 0; //load the page content with different values for display different values on html form
while(i<count) { //loop starts
$("#product").append($(this).html());
i++;
load_with_value++;
}
});
});
First of all let's do some proper code formatting and get rid of the incorrect comments:
$(document).ready(function(e) {
$("<DIV>").load("<?php echo $url; ?>", function() {
var n = $('.item').length + 1;
var i = 1;
var count = 2;
var load_with_value = 0;
while(i<count) {
$("#product").append($(this).html());
i++;
load_with_value++;
}
});
});
Now let's take it apart:
If you want to use a temporary element to store the loaded data you need to assign it to a variable, so instead of
$("<DIV>").load("<?php echo $url; ?>", function() {
do
var tempObject = $("<div/>").load("<?php echo $url; ?>", function() {
Afterwards you can append the temporary element to an existing one with $('#someExistingElement').append(tempObject).
If you want to load the content into an existing element you should use it's ID, class or other selector to do this - not $("<div>").. If you want to load it to all div elements (please don't) then it should be $("div").
Next var n = $('.item').length + 1; makes no sense. It is never used in the code.
While cycle in this case is unnecessary. Don't use while cycles if you don't have to. You can use:
for(var i=0; i<count; i++){
//code
}
What is var load_with_value = 0; used for? I can only see you incrementing it with load_with_value++; but you don't use it anywhere..
Finally if you want to load different content based on the incremented variable it should be done outside of the .load function.. For example
$(document).ready(function(){
for(var i=0; i<5; i++){
$('#container-' + i).load('/somecontent-' + i + '.html');
}
});
This loads the content /somecontent-0.html to /somecontent-4.html into container elements with IDs container-0 to container-4 respectively.

I'd like to detect the value chosen from a drop down, and then pass that to the page url and reload

I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp

Select All Text Areas And Add into one Textarea

Hello im currently writing my own javascript/PHP css editor and i have it explode the file into tags and its all echoed out into separate text areas from a loop, i was wondering if its possible to scan the page with javascript and get all the content from all the text areas and add them into one variable or one text-area, thanks in advance.
Try this:
function getTextAreasText() {
var all = document.getElementsByTagName("textarea");
var values = "";
for(var i=0; i<all.length; i++) {
values += all[i].value;
}
return values;
}
.
.
.
.
var allTexts = getTextAreasText();
Yes,
If you are familiar with jquery, this is really simple. You would do something like:
var compiled_content = '';
$.('.name_of_class_to_extract').each(function() {
compiled_content += $(this).html();
});
This would give you all HTML content from the specified class ('name_of_class_to_extract') in the variable compiled_content. You could then insert this content into another element like:
$('.class_to_inseert').html(compiled_content);
var a = "";
$("textarea").each(function(){
a += $(this).text();
$(this).prepend("<h1>" + "someValue" + "</h1>") //prepend some markup before each textarea
});
a //concatenated data
Yes possible. Edit following lines for yourself
// jquery code
$(function(){
$.ajax({
url : 'get_content_via.php',
type : 'GET',
data : 'maybe_use_filename',
success:function(data){
var splittedData = data.split("your_seperator"); // like explode
for( var i = 0 ; i < splittedData.lenght ; i++){
$('#targetInput').append(splittedData[i]);
}
}
});
});

Access GET directly from JavaScript?

I suppose I could use PHP to access $_GET variables from JavaScript:
<script>
var to = $_GET['to'];
var from = $_GET['from'];
</script>
<script src="realScript" type="text/javascript"></script>
But perhaps it's even simpler. Is there a way to do it directly from JS?
Look at
window.location.search
It will contain a string like this: ?foo=1&bar=2
To get from that into an object, some splitting is all you need to do:
var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split("=");
$_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
alert($_GET['foo']); // 1
alert($_GET.bar); // 2
Here's another idea:
<script type="text/javascript">
var $_GET = <?php echo json_encode($_GET); ?>;
alert($_GET['some_key']);
// or
alert($_GET.some_key);
</script>
I know this topic is old, but I want to share my own ES6 solution for $_GET in JavaScript.
One Liner
window.$_GET = location.search.substr(1).split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{});
Here is the MDN documentation on array.reduce(), arrow functions, the comma operator, destructuring assignment, and short-cicuit evaluation.
So, for a URL like google.com/webhp?q=foo&hl=en&source=lnt&tbs=qdr%3Aw&sa=X&ved=&biw=12 you've got an object:
$_GET = {
q: "foo",
hl: "en",
source: "lnt",
tbs: "qdr:w",
sa: "X",
ved: "",
biw: "12"
}
and you can do things like $_GET.q or $_GET['biw'] to get what you need. Note that this approach replaces duplicated query parameters with the last-given value in the search string, which may be undesired/unexpected
URLSearchParams()
Now we also have URLSearchParams() in new browsers, which lets you do things like:
window.$_GET = new URLSearchParams(location.search);
var value1 = $_GET.get('param1');
I suppose you were thinking this:
<script type="text/javascript">
var to = "<?= $_GET['to']; ?>";
var from = "<?= $_GET['from']; ?>";
</script>
...this would just be syntax-correction of your idea :)
document.get = function (d1,d2,d3) {
var divider1 = (d1 === undefined ? "?" : d1);
var divider2 = (d2 === undefined ? "&" : d2);
var divider3 = (d3 === undefined ? "=" : d3);
var url = window.location.href; //the current url
var pget = url.split(divider1)[1]; //slit the url and assign only the part after the divider 1
var pppget = {}; //define the contenitor object
if (pget.search(divider2) > -1) { //control if there is variable other than the first (?var1=a&var2=b) the var2 in this example
var ppget = pget.split(divider2); //split the divider2
for (i = 0;i==ppget.lenght; i++) { //start a for and stop it when i == at object length
if (ppget[i].search(divider3) > -1) { //control if is an empty var
psget = ppget[i].split(divider3);//if is split in 2 part using divider 3
pppget[psget[0]] = psget[1];//assign to the object the value of first element and for value the second value ex {var1=a,...}
} else {//if is a empty var (?var1&...)
pppget[ppget[i]] = "";//assign only the value of first element with value a blank string
}
}
} else {//if the url don't contain other variable
if (pget.search(divider3) > -1) { //control if is an empty var
var ppget = pget.split(divider3);//if is split in 2 part using divider 3
pppget[ppget[0]] = ppget[1];//assign to the object the value of first element and for value the second value ex {var1=a}
} else {//if is a empty var (?var1)
pppget[pget] = "";//assign only the value of first element with value a blank string
}
}
return pppget;
/* return the object
* the use of the function is like this $_GET=document.get()
* echo $_GET[var]
* or use custom divider the default is setted for php standard divider
*/};
As others have explained you can parse page URL from JS to get the variables.
You could also use AJAX in the page which submits the values. It really depends on what kind of information you're passing and then returning back to the user. (It's definitely not simpler or more direct way of doing it, just an alternative approach)
i use this one for Get request (like $_GET in php):
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
class Utils {
static HTTP_GET(key){
let map = this.HTTP_GET_ALL();
if(map.has(key)){
return map.get(key);
}else {
return null;
}
}
static HTTP_GET_ALL(){
let parts = window.location.search.substr(1).split("&");
let map = new Map();
for (let i = 0; i < parts.length; i++) {
let temp = parts[i].split("=");
map.set(decodeURIComponent(temp[0]), decodeURIComponent(temp[1]));
}
return map;
}
}
From what I can see: the URLSearchParams function is a widely-available in-built function gives you to ability to get all of the current query parameters into a single object. You can then access those parameters either individually as a replacement to $_GET, or you can foreach loop over it to make it into an array.
/* Example - Accessing a property with using URLSearchParams in place of $_GET */
const params = new URLSearchParams(window.location.search);
// Expected Output: (string) "true"
console.log(params.get("is_the_cake_a_lie"));
/* Example - Creating a $_GET array using URLSearchParams */
const params = new URLSearchParams(window.location.search);
window.$_GET = {};
for (const [key, value] of params.entries()) {
window.$_GET[key] = value;
}
// Expected Output: (object) { "is_the_cake_a_lie": "true" }, (string) "true"
console.log(window.$_GET, window.$_GET["is_the_cake_a_lie"]);
REF: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

Categories