i want to add parameters to url, for that i have 2 textbox and a button, i can't figure out where am i stuck and is unable to add parameters to url
here is my code:
HTML:
Param Name: <input id="tbAddParam" type="text" /><br>
Param Value: <input id="tbAddParamValue" type="text" /><br>
<input onclick="javascript:AddParamter();" value="Add" type="button" />
JavaScript:
function AddParamter() {
var new_url = AddUrlParameter(window.location.href, document.getElementById('tbAddParam').value, document.getElementById('tbAddParamValue').value);
window.location.href = new_url;
}
function AddUrlParameter(a, b, c) {
if (b.trim() == "") {
alert("Parameter name should not be empty.");
return a;
}
if (c.trim() == "") {
alert("Parameter value should not be empty.");
return a;
}
if (a.indexOf("?") == -1) {
return a + "?" + b + "=" + c;
}
var d = a.split("?");
if (d.length >= 2) {
if (d[1].trim() == "") {
return d[0] + "?" + b + "=" + c;
}
var e = d[1].split(/[&;]/g);
for (var f = 0; f < e.length; f++) {
var g = e[f]; var h = g.split("=");
if (h.length >= 2) {
if (h[0] == b) {
alert("Url Parameter with provided name already exists! Try Updating that Url Parameter.");
return a;
}
}
}
return a + "&" + b + "=" + c;
}
}
From the comments above:
I've tested your code and works for me (if the page ends in html, jsp or .something). This was tested using Chrome v25.
Later, I've tested on IE9 and it worked after enabling the script execution for local executed pages. A message pops up when you enter to IE. In IE9, it appears on the bottom part saying Internet Explorer restricted this webpage from running scripts or ActiveX controls. and on the right there's this option Allow blocked content..
For IE backward compatibility, it seems that you should replace the d[1].trim() as stated in james emanon's answer.
As an advice, use at least two browsers to test your web pages. And yes, I highly recommend test on IE because it will give you a good(?) feedback for being so sensitive on scripting errors (it will arise so much errors that Chrome and Firefox cover for you).
When running this in IE (I tested this in IE 10), you need to allow blocked content in order for the JavaScript to run. Otherwise the JavaScript will not be allowed to run. Luiggi Mendoza suggested the same for IE 9.
It is worth noting that this works fine in Chrome and FireFox without any user confirmation allowing JavaScript to run.
IE doesn't like ".trim()". I tested in IE8 with IE8 compat mode, and your code didn't work because of trim. Though I imagine IE9 is fine (as noted by Luigi's confirmation).
use something like this instead:
strReplace=str.replace(/^\s+/,'').replace(/\s+$/,'');
You could get around it with something like:
function stripWhiteSpace(arg){
if(arg.replace(/^\s+/,'').replace(/\s+$/,'') == ""){
return true;
}
}
then just call to it and pass your param
if (stripWhiteSpace(b))
I support #rhughes's answer. But If you test this code in IE8(I was using this and your code was not working) and below, The HTML trim() wont work. As you have trim() in 3 places, you have to use the following.
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
or you can more easly use jQuery trim()
$.trim()
refer 1
refer 2
Related
I'm an intern assisting on developing a simple landing page for our company. The main page is essentially a search bar, and as a user types if their query matches a credit union in our database, the name of that credit union is output below with a link to its page. Imagine a google-esque search bar.
This works great on desktop but for some reason, on mobile when a user types in a query, nothing comes up at all, even if they're typing something that most definitely exists in our database.
To see the site in action, it's http://mycuapp.com .
Here is the relevant HTML:
<Search></Search>
<div id = "results-bar" class="hidden"></div>
and the JS:
handleTyping(event) {
event.preventDefault();
event.stopPropagation();
const data = new FormData(event.target);
var query = event.target.value;
var url = "/search/" + query;
var i;
if (query.length >= 3) {
fetch(url, {
method: "GET",
}).then((value) => {
return value.json();
}).then((Response)=>{
var item = document.getElementById("results-bar");
if(item.className=='hidden'){
item.className = 'unhidden' ;
clickedButton.value = 'hide';
}
for (i = 0; i < Response.payload.length; i++){
var displayName = Response.payload[i].displayName;
var cuURL = Response.payload[i].url;
if(document.getElementById("results-bar").innerHTML.indexOf(displayName) == -1){ //not yet displayed in search results
var result = "<div class = 'result'><a href='" + cuURL + "'><p>" + displayName + "</p></a></div>";
document.getElementById("results-bar").innerHTML += result;
}
console.log(Response.payload[i].displayName);
}
});
}
}
render() {
return (
<form className="" id="search-form">
<input onKeyUp={this.handleTyping} type="text" autoComplete="off" name="query" placeholder="Search your credit union's name to download the mobile banking app."/>
</form>
);
}
Any insight would be greatly appreciated, including any suggestions on how to debug the problem from an iPhone (bc when simulated with Chrome's developer tools there is no issue).
EDIT: Turns out the problem is the line "const data = new FormData(event.target);" FormData is incompatible with Safari, or something. Our lead programmer caught it. Once we got rid of that line everything works great! Thanks everyone for your help.
Seems like you are trying to use Response stream which is not fully supported on Mobile Safari.
https://developer.mozilla.org/en-US/docs/Web/API/Response
Alternatively you can use fetch polyfill which is supported in Safari 6.1+
https://github.com/github/fetch
FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData
Is not compatible with Safari Mobile.
I'm using a Google Apps Script Web App and HtmlService to serve the content and I'm trying to dynamically add input elements to a form with appendChild. It works in Chrome 24 and IE 10, but Firefox 19.0.2 doesn't update the elements listing for the form.
So, it displays correctly on the webpage, but in Firefox, any input elements added with appendChild to the form aren't part of the form.elements collection. It's worth noting this issue only appears when the HTML is sanitized with Caja, if I use the same code in jsfiddle it works fine.
The issue can be seen here, which is just the following code:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function print(form)
{
var str = "";
for(var v = 0; v < form.length; v++)
{
str += "<br>" + form[v].nodeName + "." + form[v].id + ": ";
if(form[v].elements != undefined)
for(var w = 0; w < form[v].elements.length; w++)
{
str += form[v].elements[w].name + ", ";
}
}
return str;
}
function submitForm()
{
document.getElementById("nameLookupHelp").innerHTML = (print(document.forms)) + "<br>Total Elements:" + document.forms[0].elements.length;
return;
}
function onLoad()
{
var name = document.getElementById("nameForm");
var t = document.createElement("input");
t.name = "TestInput";
//t.id = "TestInput";
name.appendChild(t);
}
</script>
</head>
<body onload="onLoad()">
<form name="nameForm" id="nameForm">
<input name="nameLookup" id="nameLookup">
<input type="button" id="bntNameForm" onclick="submitForm(this)" value="Lookup">
<div class="" id="nameLookupHelp">Please enter your name.</div>
</form>
</body>
</html>
From what I've found on the subject, Firefox doesn't like invalid HTML; however, from what I can tell, the HTML output is perfectly valid. More over, since it works on jsfiddle, I assume the issue has to be with the way Caja is interacting with my HTML and Firefox.
Also, one last thing, if I inspect the form element in Firefox and double click on the form tag in the markup panel, then click off (cancel editing), Firefox then detects all of the elements and everything works fine. What Firefox displays as the HTML doesn't change though.
Thank you in advanced for your help.
Congratulations, you found a bug; a form's .elements never updates after the first time it is accessed. I have fixed it in Caja r5321.
Hello I'm using this function as an address book module, for selecting any employee from the sidebar it display all the content of the employee. It works fine in Chrome but not in IE. I'm not able to run the src variables declared in this function in IE. Please suggest me some other ways to declare these type of variables so that these will be compatible to all browsers.
function singleSelect(id)
{
if(flag){
unCheckAll();
userIds="";
//userIds= document.forms['frmSidebarSearch'].elements['userIds'].value + id +",";
var src = ($("#"+id).attr("src") === "<#core.basePath/>images/chk-box-img.gif")
? "<#core.basePath/>images/chk-box-img-tick.gif"
: "<#core.basePath/>images/chk-box-img.gif";
$("#"+id).attr("src",src);
var src2 = ($("#anchor"+id).attr("class") === "")
? "selected"
: "";
$("#anchor"+id).removeClass().addClass(src2);
var elementss = document.getElementById("all").getElementsByTagName('img');
for(i=0;i<elementss.length;i++) {
if($("#"+elementss[i].id).attr("src") === "<#core.basePath/>images/chk-box-img-tick.gif"){
userIds= userIds +"," +elementss[i].id;
}
}
unHilightAll();
highLightIndex(id);
document.forms['frmSidebarSearch'].elements['userIds'].value=userIds;
$('#frmSidebarSearch').ajaxSubmit({target:'#content',url:'<#core.basePath/>sp/manager/manageraddressbook/manager/'+id});
}
flag = true;
}
Have you tried it with double equals (I think triple equals sign is only in languages like php).
(condition == condition) ? true : false;
I have just found out after half a year that an IE cannot process this script and now that my programmer is gone I'm stuck with it myself :-(
It works fine in FF
This is the code:
function updateFields(name, value) {
var elements = getElementsByClass('field_' + name);
for(var i=0; i<elements.length; i++) {
var e = elements[i];
while(e.firstChild != null) { e.removeChild(e.firstChild); }
e.appendChild(document.createTextNode(value + ' '));*
} // for i
} // updateFields()
My IE debugger complains about the line marked with *.
It says: Error: Unexpected call to method or property access.
Can anybody spend some of his/her precious time to help?
Please write answers as if I'm a four-year-old.
function getElementsByClass(cls) {
var fields = document.getElementsByTagName('*');
var r = new Array();
for(var i=0; i<fields.length; i++) {
var f = fields[i];
var a = f.getAttribute('class');
if(a == null)
a = f.className;
if(a == null)
continue;
var classes = a.split(' ');
for(var j=0; j<classes.length; j++) {
if(classes[j] == cls) {
r.push(f);
break;
} // if
} // for j
} // for i
return r;
}
Button:
<form>
<p class="center">
<input type="button" onclick="javascript:book_wire_transfer();" style="border: none; border:0;"\>
<p class="center">
<img src="http://www.-.com/images/text/arrow_left_small.png" alt="»" class="middle" />
<span class="submit">
<input class="submit" type="submit" value="Book now" />
</span>
<img src="http://www.-.com/images/text/arrow_right_small.png" alt="«" class="middle" />
</p>
</p>
</form>
There are elements that IE8 and below cannot add textNodes to, though IE9 and other browsers do.
option element(use optionelement.text)
input element(use inputelement.value)
style element(use styleelement.styleSheet.cssText)
script element(use scriptelement.text)
getElementsByClass is not a built-in function, so it probably comes from some other library you are using that is incompatible with IE8. In this case, it is probably returning something that is not a valid set of DOM nodes.
If you could post what that method does, that would help us in debugging. Otherwise, you could try using document.querySelectorAll('.field_' + name) instead and see if that fixes it; this is supported in IE8 onwards, at least if you are in standards mode.
EDIT: your custom getElementsByClass function looks OK, although without unit tests it's hard for me to be 100% sure. One way to test would be to try and replace the body of getElementsByClass with return document.querySelectorAll('.field_' + name) and see if that fixes it... In this way, the getElementsByClass function still exists, so all your other code is not broken, but it may be more correct.
well, remove the * at the end of
e.appendChild(document.createTextNode(value + ' '));*
I have been trying to put together a proof of concept of JavaScript talking to Flash. I am using JQuery and Flash CS5, ActionScript 3.
I am not a Flash developer so apologies for the code, if I can prove this works the Flash will be given to someone who knows what they are doing.
The Actionscript is on a layer in the timeline in the first frame, with a couple of elements in the root movie:
output = new TextField();
output.y = -200;
output.x = -200;
output.width = 450;
output.height = 325;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.text = "Initializing...\n";
root.bgClip.addChild(output);
try{
Security.allowDomain("*");
flash.external.ExternalInterface.marshallExceptions = true;
output.appendText("External Interface Available? " + ExternalInterface.available + "\n");
output.appendText("External Interface ObjectId: " + ExternalInterface.objectID + "\n");
flash.external.ExternalInterface.addCallback("getMenuItems", returnMenuItems);
flash.external.ExternalInterface.addCallback("changeText", changeText);
flash.external.ExternalInterface.addCallback("changeBgColour", changeBgColour);
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
} catch (error:SecurityError) {
output.appendText("Security Error: " + error.message + "\n");
} catch (error:Error) {
output.appendText("Error: " + error.message + "\n");
}
function returnMenuItems():String{
return "[{\"menu option\": \"javascript:callFlash('changeBgColour','4CB9E4')\"}]";
}
function changeText(t:String){
root.textClip.text = t;
}
function changeBgColour(colour:String) {
var c:ColorTransform = root.bgClip.transform.colorTransform;
c.color = uint(colour);
root.bgClip.transform.colorTransform = c;
}
The JavaScript and HTML are:
function populateMenu(message){
$("#options").changeType("Options", $.parseJSON(message));
$("#options").addMenuActions();
}
function callFlash(methodToCall, param){
alert("method: " + methodToCall + ", param: " + param);
if(param == undefined){
$("#AJC")[methodToCall]();
}else{
$("#AJC")[methodToCall](param);
}
}
var flashvars = {};
var params = {allowScriptAccess: "always"};
var attributes = {name: "AJC"};
swfobject.embedSWF("http://192.168.184.128/ActionscriptJavascriptCommunication.swf", "AJC", "600", "400", "9", "", flashvars, params, attributes);
and
<body>
<div id="wrapper">
<div id="topBar" class="top-bar"></div>
<div id="flashContainer">
<div id="AJC">Loading Flash...</div>
</div>
<ul class="dropdown" id="games"></ul>
<ul class="dropdown" id="options"></ul>
</div>
</body>
Now I know the ActionScript is awful, the reason it looks like it does is because I have read a lot of threads about possible issues to do with contacting Flash from JavaScript (hence the allow security domain * and adding a debug text box etc).
The JavaScript I am using is within a script tag in the head. The changeType and addMenuActions are just JQuery methods I have added. These are just JavaScript methods that have been tested independently but do work.
You'll notice that the last line of my try catch in the ActionScript is:
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
This does work, it populate my menu with the text sent from Flash. The only thing that doesn't work is trying to call the methods exposed using the addCallback function.
I get the alert which says:
method: changeBgColour, param: 4CB9E4
but an error saying:
Error: $("#AJC")[methodToCall] is not a function
Source File: http://192.168.184.128/test.html#
Line: 88
I set up a local VM to run Apache, which relates to the 192.168.184.128, I wondering if this was the issue, I have seen a couple of threads mention that trying to communicate with flash locally won't work, which is why I set up the VM with apache?
Any ideas? I know people have got this working, it is very frustrating.
Thanks.
Simple mistake: jQuery's factory method produces jQuery.init object, which acts very similar to an array. You need to call the method on the actual DOM element, which is the first member in the "array".
$('#AJC')[0][methodToCall]
If you had security issues, you wouldn't be able to communicate between Flash and JavaScript at all.
The problem is in the way you are accessing your flash object. SwfObject has a built-in function that take care of that, it works great across all browsers:
function callFlash(methodToCall, param)
{
var obj = swfobject.getObjectById("AJC");
if(param == undefined){
$(obj)[methodToCall]();
}else{
$(obj)[methodToCall](param);
}
}
I havent tested the code above, but I guess it should work!