JavaScript userinput URL without holding my domain - javascript

I'm having a little trouble with JavaScript. My problem is that I have a user input box (where a user would enter a URL) - and a button (when clicked, it will open the URL that the user has typed in the input box).
Here is my code:
<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>
<script>
function myFunction()
{
var x = document.getElementById('userurlbox').value;
if (x == "")
{
alert('Please enter a URL');
}
else
{
window.open(x ,'_blank');
}
</script>
The problem is that the URL opens like this:
http://mywebsite.com/USERURL
I want it to open like this:
http://USERURL

This code only adds the 'http://' if it is not already included:
function myFunction() {
var x = document.getElementById('userurlbox').value;
if (x == "") {
alert('Please enter a URL');
}
else {
if (x.substr(0,4).toLowerCase() === 'http') { // only test first 4 characters as we want to allow both http:// and https://
window.open(x ,'_blank');
}
else {
window.open('http://'+x);
}
}
}

I just tested, you need to include the 'http://' in the window.open
<input type="text" id="userurlbox"/>
<button type="button" onClick="myFunction()">Open URL</button>
<script>
function myFunction(){
var x = document.getElementById('userurlbox').value;
x = x.replace('http://'.''); // remove http:// just in-case it is there
if (x == "")
{
alert('Please enter a URL');
}
else
{
window.open('http://' + x ,'_blank');
}
}
</script>

I'm not sure if you can override the relative/absolute url behavior just using the window.open function, so a viable solution would be to check if the url begins with https?:// and prepend '//' if it does not. A url starting with // will always be treated as absolute.

Related

When using a form that takes to the main website

I am doing a form window before you get in the main website so I tried to make it so that if you don't fill any of the spaces it will open a window alert asking to fill those spaces. Plus I'd like that you would only get to the main website if you fill all the spaces but yet the button on the form window always takes to the main website without requiring filling of the camps.
On the button I wrote this:
<a href="index1.html">
<input type="button" value="Terminar" onclick = location.href='index1.html' >
</a>
and on the js window I wrote the window alert command to each one of the categories:
if(frm.name.value=="" || frm.name.value==null || frm.name.length < 3) {
alert("Please write your first name ")
frm.name.focus();
return false;
It seems you are trying to validate the an input field based on a few criteria.
Your question is not clear. Is this what you are trying to do?
function validateInput() {
if (frm.value == "" || frm.value == null || frm.value.length < 3) {
alert("Please write your first name ")
frm.focus();
} else
location.href = 'index1.html'
}
<input type="text" id="frm" placeholder="Please write your first name" />
<input type="button" value="Terminar" onClick="validateInput()">
You want something like this. In your code the input is wrapped in an a tag. so it will always trigger the event. Adding a button the trigger the event will help.
button = document.getElementById('enter');
input = document.getElementById('fill');
button.onclick = function() {
if (input.value == null || input.value == "" || input.value == " ") {
alert('Please write your first name');
} else {
window.location.href = 'index1.html';
}
};
<input id="fill">
<button id="enter">Enter</button>

Either document.location or window.location.href won't work in the if part of the condition, but will work on the else part

I use the following code to validate a password in a form. If the password is correct - Move the user to site X. If it's incorrect (after 3 tries), move the user to site Y.
For some reason, it works only for site Y.
My code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
I tried doing:
Checking for syntax errors all over the code.
Changing === to == (I thought, maybe due to it being a string, the quote marks counted as well, of course I was mistaken).
window.location.href = 'http://maariv.co.il', true;
Adding return false right under window.location.href
As a beginner I ask, why would the condition works only in a half? That is, the positive part (than) doesn't work but the negative part (else) does work.
Update:
This is just an exercise. Indeed. This isn't going to production. In production I should store and request the password from a database.
Put the following line let passwordValue = document.querySelector('#user').value; inside onclick of "mybutton".
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
<form>
Enter password to continue: <br>
<input type="text" id="user" />
<input type="button" id="myButton" value="Enter site" />
</form>
Use return :
if (password === passwordValue) {
return window.location.href = 'http://maariv.co.il';
}
Otherwise, the function will execute to the end, and you will reach the second redirection, that will then override the first one.

Remove subdomain ONLY from url

How can I strip a form input URL of its subdomain and the subdomain only?
See JSfiddle or below code for example.
$('[type="button"]').click(function() {
var btn = document.getElementById("download"); //get the button
var input = $('#soundcloud-url').val();
if (input.startsWith("https://soundcloud.com/") || input.startsWith("https://m.soundcloud.com/")) {
btn.style.display = "inline-block"; //show the button
} else {
btn.style.display = "none"; //hide the button
alert('Enter a valid Souncloud url');
}
$('#soundcloud-iframe').attr('src', '//w.soundcloud.com/player/?' + $('form').serialize());
return false;
What I basically need is, if someone enters an url in the form from the mobile Soundcloud website, http://m.souncloud..., the URL converts to the normal URL automatically: without the ".m" part... But if someone enters the normal URL (non-mobile), nothing should happen.
Should be an easy fix but I cant figure it out..
You can strip out the m. subdomain with a JS replace like this:
$('#submit').on('click', function() {
var input = $('#soundcloud-url').val().replace('//m.', '//');
console.log('stripped input:', input);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
URL: <input id="soundcloud-url" value="https://m.soundcloud.com/neilcic/no-credit-card" />
<button id="submit">GO</button>

Getting value from input box, changing url based on certain conditions

Should be straightforward, but I just can't work out why this will not work! I'm a n00b, first off.
I have two input boxes that users need to fill in, a name and an amount. If these have been filled in, I change the query string on the URL, if not, then I give them a pre-defined query string for the URL.
I can't get a working jsfiddle, as something weird is going on with the & signs for my query string, sigh.
Basically, I cannot get the URL to change on click.
So here's my code, and the non-working jsfiddle for those interested: http://jsfiddle.net/9uk68m6x/
<form>
<input type="text" class="name">
<input type="text" class="amount">
<script type="text/javascript">
$(function() {
$('.makeUrl').click(function(){
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
if (nameVal != ''){
//if name value isn't blank, then
$("a.makeUrl").prop("href", url+'&name='+nameVal+'&free_amount=1&amount='+amountVal+'00');
}
else (nameVal == ''){
$("a.makeUrl").prop("href", "http://www.website.com&free_amount=1&amount=200");
}
});
});
</script>
Donate
</form>
There is a syntax error in your script: else do not accept any kind of arguments. Use else if instead. However, since your condition is binary (nameVal is either empty or not), then you can actually make do without the second if statement.
Therefore, some changes I have made:
Revise the conditional statement. You simply have to check if nameVal is empty or not using the expresison !nameVal.
Change the href attribute using .attr() instead of .prop().
Use $(this) in the click function since it is cached
Here is the fiddle: http://jsfiddle.net/teddyrised/9uk68m6x/4/
$(function () {
$('.makeUrl').click(function (e) {
// Declare variables
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
// Conditional statement
if (nameVal) {
//if name value isn't blank, then
$(this).attr("href", url + '&name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00');
} else {
$(this).attr("href", "http://www.website.com&free_amount=1&amount=200");
}
// Check updated href
console.log($(this).attr("href"));
});
});
You need to have a ? in there somewhere. A valid parameterized URL would be:
"http://www.website.com/?free_amount=1&amount=200"
Yeah, that is kinda hard to fiddle when they encode those characters for you before it runs.
After a couple changes to your JS, it seems to be working, at least in JSFiddle.
$(function () {
$('.makeUrl').click(function () {
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
if( nameVal !== "" ) {
//if name value isn't blank, then
$("a.makeUrl").prop("href", url + '?name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00');
} else {
$("a.makeUrl").prop("href", "http://www.website.com?free_amount=1&amount=200");
}
});
});
You had a syntax error at the else. Remove the (newVal == '') or use else if
Anyway, here is a working jsfiddle what is show you the URL. (Prevent to activate the link, because of e.preventDefault();
And it's checkin the amountVal also.
<form>
<input type="text" class="name">
<input type="text" class="amount">
<script type="text/javascript">
$(function() {
$('.makeUrl').click(function(e) {
e.preventDefault();
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
var newUrl;
if (nameVal !== '' && amountVal != '') {
//if name value isn't blank, then
newUrl = url + '?name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00';
$("a.makeUrl").prop("href", newUrl);
} else {
newUrl = 'http://www.website.com&free_amount=1&amount=200';
$("a.makeUrl").prop("href", "http://www.website.com?free_amount=1&amount=200");
}
$('#url').html(newUrl);
});
});
</script>
Donate
</form>
<div>URL is: <span id="url"></span></div>

How to disable a function when another one is enable?

function send() {
alert("Your message sent.");
}
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue != "" && messageValue != "") {
document.getElementById("af-form").submit();
} else {
alert("Nickname or message is blank. Please fill.");
return false;
}
}
These are my JS codes
<input type="text" name="nickname" id="input-nickname" required>
<textarea name="message" type="text" id="input-text" required></textarea>
<input type="submit" value="Send" onclick="wrongNickNameorMessage() + send()" />
And these are my HTML codes.
When I click on Send button. First alert("Your message sent."); then alert("nickname or message is blank. Please fill."); is working. Or exact opposite.
I wanna disabled send() function if wrongNickNameorMessage() is true.
How can I do that?
You have the right idea but you're going about it very out-of-the-way. Try this:
function wrongNickNameorMessage() {
var nicknameValue = document.getElementById("input-nickname").value;
var messageValue = document.getElementById("input-text").value;
if (nicknameValue === "" || messageValue === "") {
alert("Nickname or message is blank or improper input detected. Please fill.");
return false;
}
document.getElementById("af-form").submit();
alert("Your message sent.");
}
You dont need the other function or the other part of the if statement since you're just validating input. You can get more creative but that's all you really need. Your function will completely stop if there's a problem but otherwise, it'll show the right message and submit.
Although your practice is horrible, this may help you in the future:
/* first give your submit button an id or something and don't use the onclick
attribute
*/
<input type='submit' value='Send' id='sub' />
// Now the JavaScript, which should be external for caching.
var doc = document;
// never have to use document.getElementById() again
function E(e){
return doc.getElementById(e);
}
function send() {
alert('Your message was sent.');
}
// put all your sub onclick stuff in here
E('sub').onclick = function(){
var nicknameValue = E('input-nickname').value;
var messageValue = E('input-text').value;
if(nicknameValue !== '' && messageValue !== '') {
send(); E('af-form').submit();
}
else {
alert('Nickname or message is blank. Please fill.');
return false;
}
}
Note, that this is not sufficient to handle a form. It just shows concept. JavaScript can be disabled, so you must account for that as well, Server Side.
You need to call a wrapper method that will call the wrongNickNameorMessage() check result and than continue only if returned true.
function conditionalSend(){if (wrongNickNameorMessage()){send();}}

Categories