Javascript: parse parameters from URL then erase them in URL - javascript

I am trying to prefill some fields which are passed from URL as parameter pair. Having
www.example.com.com/myForm#myinput=123
as href send to end users, I am going to prefill the form field "myinput" with "123" after opening the link. However, the users will also see www.example.com.com/myForm#myInput=123 in their browser.
That's why I want to erase "myInput=123" from their URL. The reason for doing that is I don't want my users to see or even change the values in URL while filling the form.
I've tried
history.pushState(null, '', '/modifedURL')
either in HTML body "onload" or jquery "doc ready". As far I tried so far, this works only standalone without any parameter in URL like "www.example.com.com/myForm", but not with the additional injected parameters.
Here is simplified version of code what I got so far. Notice that the modifyURL Method is called successfully, but takes no effect on URL:
<head>
<meta charset="utf-8" />
</head>
<body onload="prefill();">
Your Body Content
<!-- Scripts at the bottom for improved performance. -->
<!-- jQuery, required for all responsive plugins. -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form id="myForm" method="POST">
<input id="myinput" maxlength="50" name="myinput" type="text" />
<br>
<input type="submit" name="submit" />
</form>
<script>
$(document).ready(function() {
//do some code after html is loaded
});
/*
window.onload = function () {
}
*/
function prefill() {
try{
var currentURL = window.location.href;
var n = currentURL.search("#");
var sPageURL = currentURL.substring(n+1);
var urlVal = getURLVal(sPageURL);
document.forms["myForm"]["myInput"].value = urlVal;
//change URL is called, but cannot change the URL!
modifyURL();
} catch(e){
alert("error " + e);
return false;
}
return true;
}
function modifyURL() {
history.pushState(null, '', '/modifedURL');
//even alert will fire, so pushState is skipped!!
alert('URL modified');
}
function getURLVal(query) {
//parse parameter pair in url
}
</script>
</body>

You can include the data diretly in your HTML, if it's meant to always be the same.
There are two ways:
1. <input id="myinput" maxlength="50" name="myinput" type="text" value="123" />
this actually puts the value inside your input field
2. <input id="myinput" maxlength="50" name="myinput" type="text" placeholder="123" />
this only displays it before any real value is inserted by the user (on submit you don't get any value)
I hope this is useful for you

Related

How would I go about creating this jump page?

Note: I'm a total novice at any coding. I'm just a dumb amature graphic designer. I've only ever created a page that lets me copy the
the most common phrases I had to leave in notes all day. I struggled
with it.
I'm trying to create this page that lets input something into a text field, and it applies it to defined URLS attached to buttons, that will bring me to those pages. Since I struggle to describe it, please see this visual: https://i.stack.imgur.com/ZplRK.jpg
I've tried co-opting some scripts for similar problems, but with no luck. (See below for examples before I edited them ). I included them to see if I was on the right track whatsoever. I know I'm gonna have an issue with multiple functions, probably?
<script type="javascript">
function goToPage(var url = '')
{
var initial = "http://example.com";
var extension = "html";
window.location(initial+url+extension);
}
</script>
<form name="something" action="#">
Label <input type="text" name="url" value="" onchange="goToPage(this.value)">
</form>
<SCRIPT type="javascript">
function goToPage(var url = '')
{
var initial = "https://cms.example.com/client/viewcasedetails";
var extension = "";
window.location(initial+url+extension);
}
</SCRIPT>
<TITLE>Redirect 1</TITLE>
<BASE HREF="https://cms.example.com/client/viewcasedetails">
</HEAD>
<BODY>
<P>
<FORM name="jump" action="#">
CMS ID:
<INPUT type="text" name="url" value="" onSubmit="goToPage(this.value)">
<INPUT type="submit" value="GO">
That's where I at. I'm just tired of typing the same long URLs all day at work, and messing up more than half the time. I have no clue what the solution is - Javascript? HTML? CSS? Just trying to seek the DIY answer before looking on how to hire someone to make it. Which I have no clue how to do either but that's another question for later.
Thanks for helping / apologies for possibly super dumb questions.
You could do something like the following:
// grab the input element
const input = document.getElementById("cmsId");
// grab all links that need to be updated accordingly
// when value inside input element changes
const links = document.querySelectorAll("a");
// create a handler that listens for changes when
// you type some text into the input element
input.addEventListener("input", (event) => {
// grab value inside input elemenet
const value = event.target.value;
// iterate through all links and update
// the inner text + href attribute accordingly
// NOTE: `baseUrl` for each link is stored in a
// `data-*` attribute
links.forEach((link) => {
const baseUrl = link.dataset.url;
const url = baseUrl + value;
link.innerText = url;
link.href = url;
});
});
<!-- Use a simple input element here, no need for a form -->
<div>CMS ID: <input id="cmsId" type="text" /></div>
<div>
<!-- No need to create buttons, simple anchor elements will work just fine -->
<a
id="main"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/viewclientdetails/"
>
https://cmss.company.com/client/viewclientdetails/
</a>
</div>
<div>
<a
id="notes"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/viewnotes/"
>
https://cmss.company.com/client/viewnotes/
</a>
</div>
<div>
<a
id="docs"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/documentsall/"
>
https://cmss.company.com/client/documentsall/
</a>
</div>
<div>
<a
id="activity"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/viewactivityledger/"
>
https://cmss.company.com/client/viewactivityledger/
</a>
</div>
In your code you are working with only the "main" button as I can see (as it goes to viewclientdetails). You are missing a "/" sign after var initial. So, assuming that you can implement the same functionality of the main button to the other buttons, here's what you can do:
<script type="text/javascript">
function goToPage(var url = '')
{
var initial = "https://cms.example.com/client/viewcasedetails/"; //I added the slash
var extension = "";
window.location(initial+url+extension);
}
</script>
<TITLE>Redirect 1</TITLE>
<BASE HREF="https://cms.example.com/client/viewcasedetails">
</HEAD>
<BODY>
<P>
<FORM name="jump" action="#">
CMS ID:
<INPUT type="text" name="url" value="" onSubmit="goToPage(this.value)">
<INPUT type="submit" value="GO"> //you need 4 buttons here
You cannot have an input type="submit" here, since you will need four buttons. Submit works like a form submission. Add four buttons, then for each button's onClick property add the desired redirect url. You will need to get the value for the input field using an ID tag.
An example of what I am trying to say is given below:
<script type="text/javascript">
function onMainButtonClicked()
{
var cmsid= document.getElementById("cmsID").value;
var initial = "https://cms.example.com/client/viewcasedetails/"; //I added the slash
var extension = "";
window.location(initial+cmsid+extension);
}
function onNotesButtonClicked()
{
...
}
function onDocsButtonClicked()
{
...
}
function onActivityButtonClicked()
{
...
}
</script>
<TITLE>Redirect 1</TITLE>
<BASE HREF="https://cms.example.com/client/viewcasedetails">
</HEAD>
<BODY>
<P>
<FORM name="jump" action="#">
CMS ID:
<INPUT type="text" id="cmsID" name="url" value="">
<button onclick="onMainButtonClicked()">Main</button>
<button onclick="onNotesButtonClicked()">Notes</button>
<button onclick="onDocsButtonClicked()">Docs</button>
<button onclick="onActivityButtonClicked()">Activity</button>
There are much better ways to implement this, but this is a very simple implementation.

I need to dynamically update an iframe using an input from a user

I have been searching for the right information for days and weeks now, and I must just be missing it. I have a simple problem, so it would seem. I have an iframe, which loads with a default URL. I also have a text box, and a submit button. What I want to do now, is to let the user input a URL, and then have the URL displayed in the iframe. Please don't suggest I simply do other things, or ask why I want to do this. It is a ongoing learning process.
I have a java-script function that works when I use the "onclick" function. Here is the java-script:
<script>
function setURL(url){
document.getElementById('myframe').src = url;
}
This works with a set url function such as this:
<input type="button" id="mybutton" value="Home Page" onclick="setURL('includes/guests.php')" />
The function works in that kind of scenario just fine. But, I want to instead, replace "onclick="setURL('includes/guests.php')" with the url entered by the user in this line:
<input type="text" name="sendurl" size="100">
I am unsure exactly how to get this to work right. I want the iframe to be loaded with the url the user inputs. If i use a standard submit, and submit the form to itself, the post info for the url can be checked, and i even verified it works.
if($_POST['sendurl'] != null) {
$tisturl = $_POST['sendurl'];
}
echo $tisturl;
echo $tisturl is simply to show me that it is carrying the url over correctly.
My problem is, how do I now dynamically update the iframe to the new url value?
Here is working code for something that will take what is typed by the user into a text box and use that as the src for the iFrame. Check your console to see if there are further errors (like Mixed Content security warnings, etc.).
<script>
function myFunction() {
url = document.getElementById('newURL').value;
url = url.replace(/^http:\/\//, '');
url = url.replace(/^https:\/\//, '');
url = "https://" + url;
document.getElementById('myframe').src = url;
};
</script>
<input type="button" id="mybutton" value="Home Page" onclick="myFunction()" />
<input type="text" id="newURL" />
<iframe id="myframe" src="">
</iframe>
I've updated the script to remove http:// and https://prefixes before prepending https:// to ensure it tries to fetch secure resources.
This will work. It will show the loaded URL of the iframe n the text box and it will load the URL typed in the text box to the iframe using the button in the page or the enter key on your computer.
NOTE: You do not need to have a URL, you can have anything you want, this is just an example.
JavaScript
<script language="JavaScript">
function handleKeyPress(e)
{
var key=e.keyCode || e.which;
if (key==13){
event.preventDefault();
GoToURL();
}
return false;
}
function GoToURL()
{
var URLis;
URLis = document.URLframe.u.value
test1 = document.URLframe.u1.value
test2 = document.URLframe.u2.value
// just add more of these above the more text boxes you want to use for it, or you can just have one.
{
var location= ("http://" + URLis + test1 + "anything_you_want" + test2 + ".com"); // delete or add the name of the text boxes of above.
window.open(location, 'iframefr');
}
}
</script>
Boby HTML
<form name="URLframe" id="URLframe" method="post">
<iframe name="iframefr" id="test" src="https://www.4shared.com/privacy.jsp" onload="loadurl();" width="100%" height="528px"></iframe>
<input type="text" name="u" size="71" value="" placeholder=" URL " id="SeekBox" onkeypress="handleKeyPress(event)">
<br>
<input type="text" name="u1" size="71" value="" placeholder=" U1 " onkeypress="handleKeyPress(event)">
<br>
<input type="text" name="u2" size="71" value="" placeholder=" U2 " onkeypress="handleKeyPress(event)">
<input type="button" id="SeekButton" onclick="GoToURL(this);" value=" go ">
<script type="text/javascript">
function loadurl() {
document.getElementById('SeekBox').value = document.getElementById('test').src;
}
</script>
</form>
NOTE: It is important that the function loadurl() is last in the <form>code and not in the head code as the rest of the javascript.

preventDefault and JSONP

We have a form that should post data to an external domain. We are aware of the cross-domain limitations, therefore we want to use JSONP.
All parts are working fine, except for the part that should prevent a default form submission that reloads the page. Below is the form.
The html page:
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://gateway.wildfx.com/test.js"></script>
</head>
<body>
<form method="POST" id="wild">
<fieldset>
<label for="email">Your email:</label>
<input type="text" name="email" id="wild">
<p class="wild_err">invalid</p>
<p>
<input type="hidden" id="wild_v" name="v" value="test2">
<input type="hidden" id="wild_l" name="l" value="">
<input type="hidden" id="wild_i" name="i" value="identifier">
<input type="hidden" id="wild_s" name="s" value="10612">
<input type="submit" id="wild_button" value="Check">
</p>
</fieldset>
</form>
</body>
</html>
Below is the Javascript. However, if the wild form is submitted, the page reloads instead of transfering the data with JSONp. In addition even the submission2 log isn't logged.
If tried to replace the .submit() with .click for the from button with correct ID but it isn't working either. What is wrong with the script?
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
console.log('submission1');
$("#wild").submit(function(e) {
console.log('submission2');
e.preventDefault();
if (isValidEmailAddress(e["e"])) {
var e = {};
e["e"] = $("#wild_email").val();
e["v"] = $("#wild_v").val();
e["i"] = $("#wild_i").val();
e["s"] = $("#wild_s").val();
e["l"] = $("#wild_l").val();
(function() {
var wildAPI = "https://gateway.wildfx.com/testjsonp.php?jsoncallback=?";
$.getJSON( wildAPI, {
tagmode: e,
format: "json"
})
.done(function( data ) {
$(".wild_message_container").text('Success. you are in');
setTimeout(function() {
$("#wildnotifier-container").hide();
$("#wildnotifier-overlay").hide();
}, 5000);
});
})();
} else {
$(".wild_error").show();
$("#wild_email").addClass("wild_input_error");
}
});
You load jQuery
You load your script
Your script tries to add an event handler to the form
You add the form to your page
Step 3 fails because the form doesn't exist. Move the script so it is after the form. (Or put it in a function and call it with the DOM is ready).

Populating paragraph with text from object in loop

I have a form form that either has input/select fields in form when account status is active, in this state you are able to add/edit user info, in another state Frozen, I would use the same view but replace the input and select fields with paragraph tags <p class="form-control-static"> for read-only purpose. I am populating the field when entering to EDIT mode with jQuery:
function fillFormFromObject(form, obj) {
form.find("input, select").each(
function (i, el) {
console.log(el);
$(el).val(obj[el.name]);
}
);
}
Now in paragraph case, how can I set the text for it from the object as well? Getting lost in here. I know that for paragraph element I would call text() method. But what would I pass in?
This is a proposal for a partial Answer. It includes some of the desired features, and doesn't include some others (which probably could be worked out with some experimenting).
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>test-page</title>
<script type="text/javascript">
//<!--
var f="i";
function inpdisp()
{ var d, i, x
for(x=0; x<4; x++)
{ if(x<10) //HTML code is ready for up to 100 input-fields/spans
i="0"+x;
else
i=x.toString();
d=document.getElementById("i"+i);
d.hidden = (f=="i" ? true : false);
// d.value="new value"+i; //uncomment when filling data from Server
d=document.getElementById("s"+i);
d.hidden = (f=="i" ? false : true);
// d.innerHTML="new value"+i+","; //uncomment when filling data from Server
}
f = (f=="i" ? "s" : "i");
return;
}
// -->
</script>
</head>
<body onload="inpdisp();">
<input type="button" value="inputs/displays" onclick="inpdisp();" />
<p><input id="i00" type="text" size="20" maxlength="30" value="data00" /><span id="s00">data00,</span> Type of data 00</p>
<p><input id="i01" type="text" size="20" maxlength="30" value="data01" /><span id="s01">data01,</span> Type of data 01</p>
<p><input id="i02" type="text" size="20" maxlength="30" value="data02" /><span id="s02">data02,</span> Type of data 02</p>
<p><input id="i03" type="text" size="20" maxlength="30" value="data03" /><span id="s03">data03,</span> Type of data 03</p>
</body>
</html>
That inpdisp() function is tied to a button only for "show" here. You would eliminate the button and call the function using some other criteria, in your version of this page. You will probably NOT want to modify the f variable inside the inpdisp() function, but do it elsewhere.

Need to validate form before sending

I am trying to send a form to email but I wanted the name field to be validated (if no content then don't send)
I cannot get it validate and then end through the php script I have working correctly
I have created a jsfiddle at the following link
Can someone help please?
$(document).ready(function () {
$('.form-horizontal').on('submit', function (e) {
e.preventDefault();
var name = $('#name').val();
if (!name) {
showError();
}
else {
$('#contact-form').submit();
}
});
function showError() {
$('.tyler-error').show();
}
});
Working fiddle
In your fiddle, you didn't select jQuery from the library dropdown.
Secondly, you should avoid submitting the form from within the submit handler, instead just preventDefault if there is a validation error.
$('.form-horizontal').on('submit', function (e) {
var name = $('#name').val();
if (!name) {
showError();
e.preventDefault();
}
});
If you really want to keep the code as it was, you need to call the forms submit function, not the jQuery submit function:
$('#contact-form')[0].submit();
// or
$('#contact-form').get(0).submit();
Here, [0] or .get(0) is giving you the plain JavaScript DOM element with no jQuery wrapper, and with this you can call submit().
HTML5 provides input validation, you can set in order to tell the browser that your html view is HTML5.
//Set your doctype for HTML5.
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<form id="the_form">
//here html5 will not submit if the box is empty or does not meet the email
//addres format.
<input type="email" name="email" id="email" placeholder="Enter email..">
<input type="submit" value="send">
</form>
</body>
</html>
If you dont want to use HTML5, you could also make a simple javascript code to not submit if the input is empty.
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = init();
function init(){
//get form.
var form = document.getElementById("the_form");
form.onsubmit = email_validation;
}
function email_validation(){
email = document.getElementById("email");
if(email.value == ''){
//return false to avoid submission.
return false;
}
else{
//do whatever code.
}
}
</script>
</head>
<body>
<form id="the_form">
<input type="text" name="email" id="email" placeholder="Enter email..">
<input type="submit" value="send">
</form>
</body>
</html>
with this way, your email will be validated before is sent, hope this work for you.

Categories

Resources