need a script to split and assign values Jquery - php

I am trying to separate and reassign values in a variable. What I have is
#&first=1&second=2
can anyone help with a script that will separate and assign this values to another variable so it would be like
var first= val.(first);
var second= val.(second);
I am new to jquery so I am not even sure if I am using the correct syntax.
Thanks

You could do something like this:
var val = "#&first=1&second=2";
var first = gup(val, "first");
var second = gup(val, "second");
function gup(str, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(str);
if (results == null) return "";
else return results[1];
}
Checkout the example on jsfiddle: http://jsfiddle.net/WxnJq/

Here's the one that breaks down the GET variables in to key/value pairs, which I believe is what you're after: http://snipplr.com/view/12208/javascript-url-parser/
Also, you can take a look at parseURI, a javascript function that can dissect a URL with GET parameters and grab sections.
Sorry for being quick to post, I thought I found the right function the first time.

JQuery has no builtin way of dealing with querystrings, so I use a plugin for this. You can get it here, works great.

Related

Replace special characters with alphabet in jQuery

How to remove Special Character and alphabet from variable by jQuery.
I have
var test = +985
But I want to get value as
var another = 985
It should not allow character as well + as I am using it in Phone Code
try to something like this...
var inputString = "~!##$%^&*()_+=`{}[]|\:;'<>,./?Some actual text to keep, maybe...",
var outputString = inputString.replace(/([~!##$%^&*()_+=`{}\[\]\|\\:;'<>,.\/? ])+/g, '-').replace(/^(-)+|(-)+$/g,'');
Might be duplicate of this
You just need to use replace function it's first parameter is symbol you want to replace and another is symbol or word you want to replace with.
For more info please visit Javascript replace function
var test = "+985";
var another = test.replace("+", "");
Try this to extract number:
var test = +985;
alert(test+"".match(/\d+/));

How to get variable from url for .js file?

Example: Suppose the current page url(window.location.href) is http://example.com/page.html
The html page source code is...
<html><head></head><body>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
Now I need to use 'src' variables in script.js
And the script file script.js should return
var a="Ankit"
var b="18"
Can we use something like echo $_GET like in php?
Found this here. If you're using jQuery, this should be helpful.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
This is a javascript function that will return the value in the url of a parameter that you pass to it. In this case, you would call it with
var a = getURLParameter("user");
var b = getURLParameter("ptid");
EDIT: I misinterpreted the original version of your question as asking about getting parameters to the .html page being loaded. I just tested this solution, and it does not work within the .js file itself. However, if you declare your variables in the .js file, and place this in the onLoad event, removing var from in front of a and b, it should assign the variables correctly.
Maybe outdated but a nice piece of code and would exactly do what was asked for in OP
// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
// Find all script tags
var scripts = document.getElementsByTagName("script");
// Look through them trying to find ourselves
for(var i=0; i<scripts.length; i++) {
if(scripts[i].src.indexOf("/" + script_name) > -1) {
// Get an array of key=value strings of params
var pa = scripts[i].src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
}
// No scripts match
return {};
}
Source: James Smith - Extract GET Params from a JavaScript Script Tag
I know it's an old post, but as I was looking for something like that I came across it. The very simple solution I finally adopted is the following one:
<html><head></head><body>
<script>
var a = "Ankit";
var b = 18;
</script>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
If you absolutely want to complicate your life and use Lahmizzar's solution, I would recommend to give an id to your tag script, which avoids a greedy function.
HTML :
<script src="http://example.com/script.js?user=Ankit&ptid=18" id="myScript"></script>
JS :
function getParams(script_id) {
var script = document.getElementById(script_id);
if(script) {
// Get an array of key=value strings of params
var pa = script.src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
// No scripts match
return {};
}
getParams("myScript");

Php variable to JavaScript

How to add the value of php variabele to jquery variable and adds them,i have a form that will take a value and post to second page where second page contains a div panel where the form checkboxes values are adding and subtracting,basically i want to add the submitted value from page1 to page2.Here is the code.I have 3 form values which will be redirected one by one.Whenever user submits the respective button
if($_POST['submit'])
{
$beg=$_POST['basic'];
}
function refreshPrices() {
var currentTotalValue = 0;
var beg=?????
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
var beg=<?php echo $beg; ?>
Try this:
var beg = '<?php echo $beg ;?>';
if you want to add to the total value you can do this:
currentTotalValue = currentTotalValue + parseInt(beg);
its better to do it this way :
var js_var = '<?=json_encode($php_var);?>';
This way you will be able to transfer any type of data to js (arrays, objects, strings, etc.) and access it easily like this:
js_var['element']
var beg = '<?php echo $beg ;?>';
But this can be only one once during the load of the page. After that we cant assign a server side script to js.
Retrieve value by input class or id like dat
var beg = $("#basic").val();

array of same id using getElementById error

i want to create array of same id or name using getElementById..
i have a "add button", when the user press this button, its generate a dropdown list(dynamic) which the value is get from mysql..
and its looks like this when the user press 3 times..
i want to create an array of this id, and store it to mysql..
this is my JS code :
var menu_paket_array = document.getElementById('menu_paket').value;
alert(menu_paket_array);
the problem is, when i try to create this array(menu_paket_array), the value in this array is just the first id (Test 1) only..
how can i fix this?
thanks...
Using the same id for more than one element is wrong. Id is to uniquely identify certain element. Using it for more elements defeats its -purpose. If you need that for i.e. CSS styling, then use class instead, which is designed just for such scenarios.
An ID must be unique on a page. You can only use it on one element.
Instead, use a CSS class or element type to iterate (here's a fiddle demonstrating this code):
function alertValues() {
var select, selects = document.getElementsByTagName('select');
var out = "";
for (var i = 0; i < selects.length; i++) {
select = selects[i];
if (select.className && select.className.match(/CLASSNAME_TO_INCLUDE/)) {
out += select.options[select.selectedIndex].value;
}
}
alert(out);
}
A better solution, of course, would be to utilize a dom library like jQuery or mootools, with which you could do something like this:
jQuery(function($) {
vals = [];
$('select.CLASSNAME').each(function() { vals.push($(this).val()); });
alert(vals.join(','));
});
document.getElementsByClassName(names);
Where names is the classname u generate for each one.
Instead of assigning each element with id='menu_paket' (for the reasons #WebnetMobile.com explained) assign class='menu_paket'.
Instead of var menu_paket_array=document.getElementById('menu_paket').value;, do
var temp_array = document.getElementsByClassName('menu_paket');
var menu_paket_array = [];
for(i in temp_array){
menu_paket_array[] = temp_array[i].value;
}

Getting parameters from page url

So, here's the main code, which checks the URL of the current page for the string ?a= then sets the variable ee_roomname to anything after that.
<script type="text/javascript">
var ee_roomname = unescape(location.href.substring(location.href.lastIndexOf("?a=")+1))
if(ee_roomname.indexOf("?") != -1) ee_roomname = "";
</script>
But what, if I want to add more variables, maybe after this value. For ex. here's a possible url:
http://abc.de/fg.html?a=hijk
Thus, the variable ee_roomname will be set to hijk
Now if we add some more tags, it will look like this:
http://abc.de/fg.html?a=hijk&b=lmno&c=pqrs
Now ee_roomname will be set to hijk&b=lmno&c=pqrs, which is not what I want.
I want the code to only track the a variable/parameter's value from the URL.
What needs to be changed, and how, in order to make it work?
Maybe provide a code I can use, too. (not too big fan of "do this and this" and such)
Here is a function to retrieve url parameters
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
How to retrieve the url parameters in your javascript
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
alert(first);
alert(second);
View the Source
For your bonus: if you split the string at the '?' and take the first half, that will give you the "pure" absolute url.
to answer the first question, you could also try:
<script>
var query = window.location.search.substring(1);
var getv = query.split("&");
var pair = new Array();
for (var i=0; i < getv.length; i++) {
pair[i] = getv[i].split("=");
}
</script>
pair is an array of all get variables and values like:
[["h", "1"], ["g", "2"]] if ?h=1&g=2
hope that helps.
Try to parse the entire url using this URL Parsing library in JavaScript.

Categories