Changing URL output of User Input with JavaScript - javascript

I'm trying to build something simple here:
a user types into an input field a url eg. http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com
.. hits "submit", when the URL gets spit out as a link, changing into: https://sharepointusa.com/en-us/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com
I've been trying unsuccessfully to just spit out the whole URL, losing parameters, so I need a new approach, what is an easy vanilla javascript to just replace http://sharepoint.com/ with https://sharepointusa.com/en-us/ and leave the rest of the URL?
thanks
EDIT: 2 great answers, thank you, I adapted the first answer to my original code, while I play around with the second answer to see how it compares!:
<br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
var input=document.getElementById('userInput').value;//gets the value entered by user
const updatedUrl = input.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
document.getElementById("link").href = updatedUrl;
document.getElementById("link").innerHTML = updatedUrl;
}
</script>

if you have a variable containing the full original url
const url = 'http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com';
then you can just do
const updatedUrl = url.replace('http://sharepoint.com/', 'https://sharepointusa.com/en-us/');
and updatedUrl will have what you're asking for.

It1 got it right before me! anyways, this is a more advanced representation of how to change it directly from the input fields.
<!DOCTYPE html>
<html>
<body>
<input id="demo" value="http://sharepoint.com/human-resources/usa/Lists/testList/EditForm.aspx?ID=666&Source=http%3A%2F%sharepoint.com">
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").value;
var changed = str.replace("sharepoint", "sharepointusa");
document.getElementById("demo").value = changed;
}
</script>
</body>
</html>

Related

Dynamic Heading Update - HTML and Javascript using query string [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 months ago.
You need to show the user's name in the heading. The heading should say Hello, (user) when the user enters their name into the text box which is a simple form input and presses the button.
To display the user's name, you'll need to read the user's name from the query string. You need to read the query string when the page is loaded, not when the button is pressed.
I need to implement this using javascript and query string but I haven't got a clue how.
<form>
<input type="text" name="user_name" placeholder="Enter your name!" />
<button type="submit">Apply!</button>
</form>
<input type="text" placeholder="Enter name." id="txtname">
<button onclick="Submit()">Apply!</button>
After clicking on apply button displayUser.html page will open containing
<script>
function Submit() {
let name = document.getElementById("txtname").value;
window.location.href = "displayUser.html?user=" + name;
}
</script>
displayUser.html
<html>
<head>
<title>About</title>
<script>
function sayHellow() {
//to read query string
let params = new URLSearchParams(window.location.search);
let values = [];
for (const value of params.values()) {
//putting values in array
values.push(value);
}
console.log(values);
document.write("<h2>Hellow! "+values[0]+"</h2>")
}
</script>
</head>
<body onload="sayHellow()">
</body>
</html>
firstpage.html
<input type="text" id="titletxt">
<button onclick="Submit()">Submit</button>
<script>
function Submit() {
let name = document.getElementById("txtname").value;
window.location.href = "secondpage.html?" + name;
}
</script>
secondpage.html
<html>
<head>
<title>Test</title>
<script>
function loadTitle() {
let queryString = window.location.search.split('?')[1];
document.write("<h2>Hello "+queryString+"</h2>")
document.title = "hello "+queryString;
}
</script>
</head>
<body onload="loadTitle()">
</body>
</html>

Set to true state a checkbox in a different page(javascript)

Here's the Script.
javascript
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
$('#website-design').attr('checked',true);
window.location.href = "/contact";
}
}
}
I want to check my checkboxes when I click the button with an id=website-design-check.
Here is my HTML.
first.html
<a href="/contact" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
Here's the second HTML file where checkbox is.
second.html
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
Now how can I achieve what I want base on the description given above. Can anyone help me out guys please. I'm stuck here for an hour. I can't get any reference about getting a checkbox state from another page.
To do this, you can modify your button link and add in additional parameters that you can then process on the next page.
The code for the different pages would be like:
Edit: I changed it to jQuery, it should work now.
Script
function linkPageContact(clicked_id){
if(clicked_id === 'website-design-check'){
window.location.href = "second.html?chk=1";
}
}
second page
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script type="text/javascript">
var url = window.location.href.split("?");
if(url[1].toLowerCase().includes("chk=1")){
$('#website-design').attr('checked',true);
}
</script>
since your checkbox is in another html page, so it's totally normal that you can't get access to it from your first html page!
what I can offer u is using the localstorage to keep the id and then use it in your second page to check if it's the ID that u want or not.
so change your function to this :
function linkPageContact(clicked_id){
localStorage.setItem("chkId", "clicked_id");
window.location.href = "/contact";
}
then in your second page in page load event do this :
$(document).ready(function() {
var chkid = localStorage.getItem("chkId");
if(chkid === 'website-design-check'){
$('#website-design').attr('checked',true);
});
You can't handle to other sites via JavaScript or jQuery directly. But there's another way. You can use the GET method to achive this.
First you need to add to the link an attribute like this in your first.html:
/contact?checkbox=true
You can change the link as you want with JavaScript.
Now it will refer to the same page but it can be now different. After that you can receive the parameter with this function on the second.html.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
I got it from this post thanks to Bakudan.
EDIT:
So here is an short theory.
When the user clicks the button on the first page, then you change the link from /contact to /contact?checkbox=true. When the user get forwarded to second.html then you change the checkbox depending on the value, which you got from the function findGetParameter('checkbox').
As all have mentioned you need to use session/query string to pass any variable/values to another page.
One click of the first button [first page] add query string parameter - http://example.com?chkboxClicked=true
<a href="secondpage.html?chkboxClicked=true>
<button>test button</button>
</a>
In the second page- check for the query string value, if present make the checkbox property to true.
In second page-
$(document).ready(function(){
if(window.location.href.contains('chkboxClicked=true')
{
$('#idOfCheckbox').prop('checked','checked');
}
})
Add it and try, it will work.
Communicating from one html file to another html file
You can solve these issue in different approaches
using localStorage
using the query parameters
Database or session to hold the data.
In your case if your application is not supporting IE lower versions localStorage will be the simple and best solution.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<a href="contact.html" target="_blank">
<button type="button" class="btn btn-success btn-block" id="website-design-check" onclick="linkPageContact(this.id)">Appointment</button>
</a>
<script>
function linkPageContact(clicked_id) {
localStorage.setItem("chkId", clicked_id);
}
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" aria-label="Checkbox for following text input" id="website-design" name="website-design">
<script>
$(document).ready(function () {
var chkid = localStorage.getItem("chkId");
if (chkid === 'website-design-check') {
$('#website-design').attr('checked', true);
}
});
</script>
</body>
</html>

Missing POST parameters in AJAX call result in undefined index warnings in PHP script

I am using AJAX for the first time so I write a code and I followed a tutorial, but when I try to send my post with ajax I am getting undefined index and I really don´t know why, I tried to search answer hear but since I am using AJAX and javascript for the first time, the code there didn´t tell me anything.
Here is my code, I would be really greatful for any help, thank you.
js method
function post() {
var name = $('meno').val();
var priez = $('priezvisko').val();
$.post( "aktualizuj.php", {
'meno': name,
'priezvisko': priez
},
function (data) {
$('#result').html(data);
}
);
}
html form...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="prihlasenie.js"></script>
</head>
<body>
<form>
<label for="meno" >Meno:</label><input type ="text" name="meno" id="meno" value ="meno" ><br>
<label for="priezvisko" >Priezvisko:</label><input type ="text" id="priezvisko" name="priezvisko" value ="priezvisko" ><br>
<input type="button" value="ulozZmeny" onclick="post()" >
</form>
<div id="result"></div>
</body>
</html>
this where I should get from ajax/javascript
session_start();
require "pripojenie.php";
$meno = $_POST['meno'];
$priezvisko = $_POST["priezvisko"];
$login = $_SESSION['login'];
jquery doesn't serialize key:value pairs where value is undefined, i.e.
$.post(url, { foo:undefined });
results in jquery not sending any POST parameter.
The problem is because of the following lines,
var name = $('meno').val();
var priez = $('priezvisko').val();
This would look for an element meno and an element priezvisko (and then their values) as if you had a document like
<p>
<meno>...</meno>
<priezvisko>...</priezvisko>
</p>
But you're looking for elements that have meno/priezvisko as value of their id attribute(s):
var name = $('#meno').val();
var priez = $('#priezvisko').val();
You should nevertheless check the existince of the parameters in your php script. Nothing prevents another script/bot/user to invoke your script with different parameters or no parameters at all.
see also:
http://docs.php.net/isset
http://docs.php.net/filter

How to display image using javascript

How to display an image as many times as input(number) given by the user in html using javascript? There seem to be an error in my code,dont know how to rectify.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag(c,x)">Try it</button>
<p id="demo"></p>
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<p id="demo"></p>
<script>
function imag() {
var x = document.getElementById("myNumber").value;
var c = '\<img src="http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg"\/\>';
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
</script>
</body>
</html>
Notice that I just changed <button onclick="imag(c,x)">Try it</button> to <button onclick="imag()">Try it</button>; and I switched your apostrophes here: var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
You told javascript that imag() should get two variables. but you never gave the function actual variables (and you filled them inside the function). so I removed the variables from the function's deceleration.
second thing I did was change the Quotation marks and Apostrophes since HTML standards require Quotation marks for the tags' content. switching between them allows you to keep the HTML standard.
The .innerHTML property takes a string. So, you need to convert your array to a single string like this:
document.getElementById("demo").innerHTML = arr.join("");
Note that 'C:/Users/Akhil/Desktop/New folder/G.jpg' is generally not a valid URL to refer to your image so you may need to fix that too. You can read here to see how file URLs work: http://en.wikipedia.org/wiki/File_URI_scheme
And, there's no reason to pass two empty variables to your imag() function. You can change this:
<button onclick="imag(c,x)">Try it</button>
to this:
<button onclick="imag()">Try it</button>
Firstly, you call imag function with the c and x, but the code doesn't know anything about them. That's why you get a TypeError.
You should create an event handler for the click event of the button, not this inline handler, where you can pass whatever you like at values of x and c.
Check this plunk here
And lastly, the innerHTML property takes a string (HTML or plain text). But in this case it will join all your values, comma separated, because the toString method of the array is invoked. Reference here
Your variables x and c are undefined, there is nothing in it so your code breaks. This is how parameters work, you give them a value and pass them to the function, so c becomes 'hello' and x becomes 5, fiddle:
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag('hello',5)">Try it</button>
<p id="demo"></p>
Javascript
function imag(c,x) {
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr;
}
}
But this is not very flexible right? So your solution is already stated in other answers. You don't pass in parameters and make the variables in the function everytime you click on the button and please stop using inline calls. It is really outdated, messy and unnecessary! Learn how to use eventhandlers.

External JavaScript file issues

Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;

Categories

Resources