My WebApp where withSuccessHandler returns undefined - javascript

I need help sorting this out. Everything seems to work fine until it gets to receive the results of request, where someting goes wrong. The idea of the project is a Web App, where user gets 2 fields for name and date of birth. After filling them the information is verified by checking in the spreadsheet with relevant information. If everything is okay, the program next obtains appropriate id with getSheetId(), generates <iframe> code for access and should be returning it with HtmlService. However, something makes it return undefined.
Code.gs
function doGet() {
Logger.log("Login is loading")
return HtmlService
.createTemplateFromFile('index')
.evaluate()
//.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function evaluate(name, date) {
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho')
.getSheetByName('key');
Logger.log(t.getSheetId());
Logger.log(name);
Logger.log(date);
var v = t.getRange("B2:D200");
var i = 0;
for (i = 1; i < 200; i++) {
if (v.getCell(i, 2).getValue() == name) {
Logger.log(v.getCell(i, 2).getValue());
Logger.log(name & " = the name");
Logger.log(new Date(v.getCell(i,3).getValue()).getTime());
var pdate = date.split(".");
Logger.log(new Date(pdate[2],pdate[1],pdate[0]).getTime());
var t = v.getCell(i,3).getValue();
Logger.log(pdate);
Logger.log(t.getFullYear());
Logger.log(t.getMonth());
Logger.log(t.getDate());
if (new Date(t.getFullYear(),t.getMonth()+1,t.getDate()).getTime() == new Date(pdate[2],pdate[1],pdate[0]).getTime()) {
Logger.log("match found");
include(v.getCell(i,1).getValue());
break;
} else {
Logger.log("Bad date");
return "<h2>Wrong Input. 404.</h2>";}
}
}
if (i >= 199) {
Logger.log("Bad name");
return "<h2>Wrong Input. 404.</h2>";
}
}
var hhtml = "";
function include(name) {
var html = '<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTeFjXOSsBRAKjbFLUSBGZOXtmjZO_4RtxxrQtXbk9sxZkF5Kdjs9OIs0tSQwekjYbOTn7JJ-_iCdeD/pubhtml?gid='
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho').getSheetByName(name);
if (t == null) {
Logger.log("Page not found");
return "<h1>Wrong Input. 404.</h1>"
} else {
html += t.getSheetId();
}
Logger.log(name);
html += '&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
html += '<br><br><br><h3>Рейтинг групи</h3><iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRF1MobEoKdxvO_SopGTvl-WzqEQ3nQXd6Jo_a7RTAg09yluO32AClwd4krWnVHXGQllPPwOsDeYYzN/pubhtml?gid=2096708929&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
Logger.log(html);
hhtml = HtmlService.createHtmlOutput(html).getContent();
return HtmlService.createHtmlOutput(html).getContent();
}
function getHtmlCode() {
return hhtml;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="mainForm">
<h2> Будь-ласка введіть своє прізвище українською мовою та дату народження у форматі день.місяць.рік (наприклад: 22.06.2018) </h2>
<form>
<div>
<div class="inline form-group">
<label for="name">Прізвище</label>
<input type="text" id="nameInput" style="width: 150px;">
</div>
<div class="inline form-group">
<label for="date">Дата Народження</label>
<input type="text" id="dateInput" style="width: 150px;">
</div>
</div>
<button class="action" type="button" id="submitButton">Submit</button>
</form>
</div>
<style>
.hidden {
display:none;
}
.form-group {
margin: 2px 0px;
}
#submitButton {
margin: 4px 0px;
}
body {
margin-left: 50px;
}
</style>
<script>
$(function(){
console.log('startup')
$('#submitButton').on('click', function(){
console.log("data get");
function respondent(value)
{
$('#mainForm').toggleClass('hidden');
console.log("script is success");
console.log(value);
document.getElementById('Response').innerHTML = value
}
google.script.run.withSuccessHandler(respondent).evaluate(document.getElementById('nameInput').value, document.getElementById('dateInput').value);
})
})
</script>
<div id="Response">
<h2>Waiting for data...</h2>
</div>
</body>
</html>

After cleaning up your code formatting, it looks like you're only returning a value from evaluate() during the Wrong Input error conditions. Nothing is returned otherwise.
Perhaps you meant to add a line like this at the end of evaluate():
return include(name);
Also, the hhtml global variable and getHtmlCode() functions aren't useful in the context of Apps Script. Each execution is in a separate instance with no state being carried over. Which mean getHtmlCode() will always return an empty string.

Related

Input value not updating on page when changed

I have to do a web page for school that converts temperature between celsius and fahrenheit.
I tried to make it with 2 input boxes that change value based on the value of the other input box, when I write something on one of the input boxes for the first time it works, but then even though on the code the value changes, on the page it doesn't appear.
I am new to javascript and html in general and I don't know what I'm doing wrong.
This is the code:
function cambiagradi(x,y) {
if (document.getElementById(x).value == "Centigradi") {
document.getElementById(y).value = "Fahrenheit";
}
else {
document.getElementById(y).value = "Centigradi";
}
}
function Conversione(from,to,gradi) {
var x = document.getElementById(from).value;
if (document.getElementById(gradi).value == "Centigradi") {
document.getElementById(to).setAttribute("value", (x-32)*5/9);
}
else {
document.getElementById(to).setAttribute("value", (x*9/5)+32);
}
}
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #008080;">
<h1 style="text-align:center">Convertitore Temperatura</h1>
<div class="container" style="display:flex; justify-content: center">
<div style=" padding: 1%; ">
<p>
<input type="text" id="box1" oninput="Conversione('box1','box2','Gradi2')">
</p>
<p style="margin-left:10%">
<label for="Gradi1">Gradi</label>
<select id="Gradi1" onchange="cambiagradi('Gradi1','Gradi2')">
<option value="Centigradi">Centigradi</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</p>
</div>
<div style=" padding: 1%; ">=</div>
<div style=" padding: 1%; ">
<p>
<input type="text" id="box2" oninput="Conversione('box2','box1','Gradi1')">
</p>
<p style="margin-left:10%">
<label for="Gradi2">Gradi</label>
<select id="Gradi2" onchange="cambiagradi('Gradi2','Gradi1')">
<option value="Fahrenheit">Fahrenheit</option>
<option value="Centigradi">Centigradi</option>
</select>
</p>
</div>
</div>
</body>
</html>
Thanks in advance!
You should just set the value of the element and all would work as expected.
The explanation you can find here.
function Conversione(from, to, gradi) {
const x = document.getElementById(from).value;
if (document.getElementById(gradi).value == "Centigradi") {
document.getElementById(to).value = ((x - 32) * 5) / 9;
} else {
document.getElementById(to).value = (x * 9) / 5 + 32;
}
}
Some explanations within the code. Tell me if you need more. It looks more complicated but it avoids inline JavaScript which is good :)
// Define your elements as variables first as you're going to use them multiple times :
const gradi1 = document.getElementById("Gradi1");
const gradi2 = document.getElementById("Gradi2");
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
// Now, always use gradi1, gradi2, box1 and box2 instead of document.getElementById ....
// Then, avoid INLINE JavaScript ! (onchange="")
// We're gonna add 'event listener' to your elements
gradi1.addEventListener("change", function(){
cambiagradi(this); // 'this' means you'll know which element triggered the event when calling the function
}, false);
gradi2.addEventListener("change", function(){
cambiagradi(this);
}, false);
box1.addEventListener("input", function(){
Conversione(this)
}, false);
box2.addEventListener("input", function(){
Conversione(this)
}, false);
// You passed 'this' previously, so its back here with the name you want (ex: ancora_this)
function cambiagradi(ancora_this) {
if (ancora_this.id == "Gradi1") {
if (ancora_this.selectedIndex == 0) { // 'selectedIndex' means selected option position in the dropdown menu (begins at 0)
gradi2.selectedIndex = 1;
} else {
gradi2.selectedIndex = 0;
}
} else {
if (ancora_this.selectedIndex == 1) {
gradi1.selectedIndex = 0;
} else {
gradi1.selectedIndex = 1;
}
}
}
function Conversione(ancora_this) {
var target, conv, unit;
if (ancora_this.id == "box1") {
target = box2;
unit = gradi1;
} else {
target = box1;
unit = gradi2;
}
if (unit.selectedIndex == 0) {
conv = (Number(ancora_this.value) * 9/5) + 32;
} else {
conv = (Number(ancora_this.value) - 32)*5/9;
}
target.value = conv;
}
body {
background-color: #008080
}
h1 {
text-align: center
}
.container {
display: flex;
justify-content: center
}
.container div {
padding: 1%;
}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Convertitore Temperatura</h1>
<div class="container">
<div>
<p>
<!-- type="number" is better because it only allows numbers -->
<input type="number" id="box1">
</p>
<p style="margin-left:10%">
<label for="Gradi1">Gradi</label>
<select id="Gradi1">
<option value="Centigradi" selected>Centigradi</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</p>
</div>
<div>=</div>
<div>
<p>
<input type="number" id="box2">
</p>
<p style="margin-left:10%">
<label for="Gradi2">Gradi</label>
<select id="Gradi2">
<!-- I switched the order to have the same 'index' on both SELECT menus
Also, I added 'selected' to have a default selected unit at start -->
<option value="Centigradi">Centigradi</option>
<option value="Fahrenheit" selected>Fahrenheit</option>
</select>
</p>
</div>
</div>
</body>
</html>

how can I measure a surface of a circle with input in javascript?

Can someone tell me everything wrong with my code?
const PI = 3.14;
function povrsina(r) {
if (!null) {
return (r * r) * PI;
}
}
function prikazivanje(event) {
event.preventDefault();
var poluP = document.getElementById("broj");
var poluP2 = poluP.value;
var r = parseFloat(poluP2);
var povrsina = povrsina(r);
var rezultat = document.getElementById("rezultat");
rezultat.innerHTML = povrsina;
}
var dugme = document.getElementById("izracunaj");
dugme.addEventListener("click", prikazivanje);
<!DOCTYPE html>
<html>
<head>
<title>Povrsina kruga</title>
<meta charset="UTF-8">
</head>
<body style="background-color: #DDDDDD">
<header>
<div style="background-color: silver; text-align: center">
<h1>Povrsina kruga</h1>
</div>
</header>
<section>
<form style="text-align: center">
<label for="broj">Unesi poluprecnik</label>
<input type="text" id="broj" />
<button id="izracunaj">Izracunaj</button>
</form>
<h1 style="text-align: center">
Resenje: <span id="rezultat"></span>
</h1>
</section>
</body>
</html>
When the button is clicked, if the input is null I don't want anything to happen, but if it has a number I want the answer to be right next to "Resenje: "
var povrsina = povrsina(r);
In line 54, name your variable something different. The error is being created because your variable name is being used as a function as well.
if(!null) {
return (r * r) * PI;
}
You should also change your if statement to something like if(r != undefined){...}.

elasticlunr.js not showing results for search query

I used elasticlunr.js search engine.
I edited their example source code
$('input').bind("enterKey", function (e) {
var value_test = $("#inputSuccess1").val();
if ($(this).val() < 2) return
var config = $('#configuration').val();
config.trim();
var json_config = null;
if (config != '') {
json_config = new elasticlunr.Configuration(config, idx.getFields()).get();
}
var query = value_test;
var results = null;
console.log(query);
if (json_config == null) {
results = idx.search(query).map(function (result) {
console.log(result);
return questions.filter(function (q) {
console.log(q);
return q.page_id === parseInt(result.ref, 10)
})[0]
})
} else {
results = idx.search(query, json_config).map(function (result) {
return questions.filter(function (q) {
return q.page_id === parseInt(result.ref, 10)
})[0]
})
}
renderQuestionList(results);
console.log(results);
});
All stored search results are displayed on load but when I enter a search query, it returns the supposed un-edited search results. Though the search result array is populated (for e.g.) by 2 items , it is still undefined. I tried to put my own result (just 1) on the example_index.json and tried to input tags relevant to it. It still doesn't show.
HTML CODE
<body>
<div id="wrapper">
<main class="main" role="main" style="margin-top: 30px">
<div class="container">
<div class="row">
<header style="margin-left: 15px; margin-right: 15px;">
<h1>Elasticlunr<span>.js</span></h1>
<h2>Lightweight full-text search engine in Javascript for browser search and offline search.</h2>
</header>
</div>
<div class="row">
<div class="col-md-6">
<span><strong><i>Search Configuration:</i></strong></span>
<textarea id="configuration" class="form-control" rows="6" style="font-size: 0.8em;"></textarea>
</div>
<div class="col-md-6" style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;">
<span><strong><i>Configuration Example:</i></strong></span>
</div>
</div>
<div class="row" style="margin-left: 0px; margin-right: 0px; border-top-style: solid; border-top-width: 0px; padding-top: 10px;">
<div class="col-md-6" style="padding-left: 0px; padding-right: 50px">
<form>
<div class="form-group has-success">
<div class="col-xs-9" style="padding-left: 0px;">
<input type="search" class="form-control" id="inputSuccess1" >
</div>
</div>
<div><a class="all btn btn-primary btn-block" href="#">All</a></div>
</form>
</div>
<div class="col-md-12" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid rgba(7, 94, 115, 0.3); padding-left: 0px;"></div>
</div>
<div class="row" style="margin-left: 0px; margin-right: 0px;">
<div class="col-md-6" style="margin-left: 0px; margin-right: 0px;">
<div id='question-list-container' style="margin-left: 0px; margin-right: 0px;"></div>
</div>
<div class="col-md-6" style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;">
<div id='question-view-container' style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;"></div>
</div>
<div class="col-md-12" style="padding-bottom: 15px; border-bottom:1px solid rgba(7,94,115,0.3);"></div>
</div>
</main>
</div>
<!-- end of wrapper -->
<!-- Begin footer -->
<footer class="footer vertical-center">
<div class="container">
<p class="pull-right text-muted">Back to top
</p>
<p class="text-muted">Copyright © Wei Song 2015.
https://github.com/weixsong watkinsong#163.com. Donate by Alipay: watkinsong#163.com</p>
</div>
</footer>
<script>
(function(hijs) {
//
// hijs - JavaScript Syntax Highlighter
//
// Copyright (c) 2010 Alexis Sellier
//
// All elements which match this will be syntax highlighted.
var selector = hijs || 'pre';
var keywords = ('var function if else for while break switch case do new null in with void ' + 'continue delete return this true false throw catch typeof with instanceof').split(' '),
special = ('eval window document undefined NaN Infinity parseInt parseFloat ' + 'encodeURI decodeURI encodeURIComponent decodeURIComponent').split(' ');
// Syntax definition
// The key becomes the class name of the <span>
// around the matched block of code.
var syntax = [
['comment', /(\/\*(?:[^*\n]|\*+[^\/*])*\*+\/)/g],
['comment', /(\/\/[^\n]*)/g],
['string', /("(?:(?!")[^\\\n]|\\.)*"|'(?:(?!')[^\\\n]|\\.)*')/g],
['regexp', /(\/.+\/[mgi]*)(?!\s*\w)/g],
['class', /\b([A-Z][a-zA-Z]+)\b/g],
['number', /\b([0-9]+(?:\.[0-9]+)?)\b/g],
['keyword', new(RegExp)('\\b(' + keywords.join('|') + ')\\b', 'g')],
['special', new(RegExp)('\\b(' + special.join('|') + ')\\b', 'g')]
];
var nodes, table = {};
if (/^[a-z]+$/.test(selector)) {
nodes = document.getElementsByTagName(selector);
} else if (/^\.[\w-]+$/.test(selector)) {
nodes = document.getElementsByClassName(selector.slice(1));
} else if (document.querySelectorAll) {
nodes = document.querySelectorAll(selector);
} else {
nodes = [];
}
for (var i = 0, children; i < nodes.length; i++) {
children = nodes[i].childNodes;
for (var j = 0, str; j < children.length; j++) {
code = children[j];
if (code.length >= 0) { // It's a text node
// Don't highlight command-line snippets
if (!/^\$/.test(code.nodeValue.trim())) {
syntax.forEach(function(s) {
var k = s[0],
v = s[1];
code.nodeValue = code.nodeValue.replace(v, function(_, m) {
return '\u00ab' + encode(k) + '\u00b7' + encode(m) +
'\u00b7' + encode(k) + '\u00bb';
});
});
}
}
}
}
for (var i = 0; i < nodes.length; i++) {
nodes[i].innerHTML =
nodes[i].innerHTML.replace(/\u00ab(.+?)\u00b7(.+?)\u00b7\1\u00bb/g, function(_, name, value) {
value = value.replace(/\u00ab[^\u00b7]+\u00b7/g, '').replace(/\u00b7[^\u00bb]+\u00bb/g, '');
return '<span class="' + decode(name) + '">' + escape(decode(value)) + '</span>';
});
}
function escape(str) {
return str.replace(/</g, '<').replace(/>/g, '>');
}
// Encode ASCII characters to, and from Braille
function encode(str, encoded) {
table[encoded = str.split('').map(function(s) {
if (s.charCodeAt(0) > 127) {
return s
}
return String.fromCharCode(s.charCodeAt(0) + 0x2800);
}).join('')] = str;
return encoded;
}
function decode(str) {
if (str in table) {
return table[str];
} else {
return str.trim().split('').map(function(s) {
if (s.charCodeAt(0) - 0x2800 > 127) {
return s
}
return String.fromCharCode(s.charCodeAt(0) - 0x2800);
}).join('');
}
}
})(window.hijs);
</script>
3rd edit:
I have this code
$('input').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
I use xampp and when I press enter this is what happens. those "Empty list" are from the previous .json file but with a different id . I can't find that part
it has a lot of codes so i uploaded it here (edited: removed link. fixed now)
The input tag exists in between the form tag. This implies that upon pressing enter the form is submitted and therefore the page reloads thus removing any information you placed and showing the unadulterated results .
In the example provided by the developer, $('input').bind('keyup', debounce(function () { is used. Therefore, upon entering text the tags are searched. However, in your case, the control doesn't even shift to code that you are intending to run.
Please check this
https://jsfiddle.net/kaminasw/rqj68xt5/ where it should show alert upon pressing enter in the input.
$('input').bind("enterKey",function(e){
alert();
});
Try to use the actual code with keyup event and compare the pressed key with enterKey code i.e. 13.
$('input').keyup(function(e) {
// 13 is ENTER
if (e.which === 13)
// Perform action
});
I read the manual and missed and ingnored the node.js part. As you can see the index_builder.js uses fs, which I learned, that uses node.js. You have to use node.js and run index_builder.js. This will build an index.json file from your data.json(stored search results). The code uses the example source code I have to rebuild the index. Also, I am using xampp for local host.
Step 1. Download and Install node.js
Step 2. Run Xampp Shell on elasticlunr project directory
Step 3. Type in node index_builder.js
Step 4. Elastic Search will work with the entered query
This is the code of my index_builder.js
var elasticlunr = require('./elasticlunr.js'),
fs = require('fs');
var idx = elasticlunr(function () {
this.setRef('page_id');
this.addField('title');
this.addField('tags');
this.addField('body');
this.addField('url');
});
fs.readFile('./example_data.json', function (err, data) {
if (err) throw err;
var raw = JSON.parse(data);
var questions = raw.questions.map(function (q) {
return {
page_id: q.page_id,
title: q.title,
body: q.body,
url: q.url,
tags: q.tags.join(' ')
};
});
questions.forEach(function (question) {
idx.addDoc(question);
});
fs.writeFile('./example_index.json', JSON.stringify(idx), function (err) {
if (err) throw err;
console.log('done');
});
});
Thanks!

Calling function from anonymous function in JQuery returns undefined

I'm working with this script which needs to call the external function, but the value returned in the log shows 'undefined'.
I have a checkbox that calls the external function successfully, but the anonymous jQuery function is not successful. Could this be a scope issue of some sort?
Thanks for any help.
css:
div.row {
border: 1px solid blue;
width: 100px;
}
div.child {
border: 1px solid red;
display: inline-block;
}
javascript:
function padZeros(ksa) {
getDigits(ksa);
//alert(s);
//document.getElementById("ksa_padded").value=s
}
function getDigits(MyDigits) {
var ksa = MyDigits;
var re4Digit = /^([0-9])([0-9]?)([k|s|a])([0-9])([0-9]?)([A-z]?)$/;
var first2Digits = ksa.replace(re4Digit, "$1$2");
//alert(first2Digits);
//return first2Digits;
pad(first2Digits, '2');
}
function pad(num, size) {
//var s = num+"";
//alert(num);
s = num + "";
//alert(s);
while (s.length < size) s = "0" + s;
return s;
//alert(s);
}
$("#add").click(function () {
var inserted = false;
var newText = $("#addText").val();
var $newItem = $("<div class='child'>" + newText + "</div>");
$(".row:first .child").each(function () {
//alert($(this).text());
xx = $(this).text();
var compare_a = padZeros(xx);
//alert(compare_a);
console.log(xx);
if ($(this).text() > newText) {
$newItem.insertBefore($(this));
inserted = true;
return false;
}
});
if (inserted == false) {
$newItem.appendTo(".row:first");
}
});
html
<div class="row">
<div class="child">3K1</div>
<div class="child">3K3</div>
<div class="child">3K4</div>
<div class="child">1K1</div>
<div class="child">1K2</div>
</div>
<div class="row">
<div class="child">IS2</div>
<div class="child">IS4</div>
</div>
<div class="row">
<div class="child">IA2</div>
<div class="child">IA4</div>
</div>
<br/>
<input id="addText" type="text" />
<input id="add" type="button" value="Insert Element" />
<br>
<input type="checkbox" onClick="padZeros('1k10s')">
<input type="text" id="ksa_padded">
Try
return getDigits(ksa);
return pad(first2Digits,'2');
You have to return things, otherwise they'll come out as undefined.

Validate URL entered by user

I have already checked previous answers on the SO. I know they are cool.
Here is my chance:
I am taking values of textbox and passing it to function to validate. It passes url correctly but not doing validations. Can someone check where is the bug? I could not identify
<html>
<head>
<title>ThenWat</title>
<script>#Vicky: above regex does not filter:
function validateURL($URL) {
alert($URL);
$pattern_1 = "/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
$pattern_2 = "/^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i";
if(preg_match($pattern_1, $URL) || preg_match($pattern_2, $URL)){
alert("correct");
return true;
} else{
alert("Incorrect");
return false;
}
}
</script>
</head>
<body style="height: 560px">
<form>
<label>Enter URL: <input type="text" value="http://www.paulgraham.com/herd.html" name="sent" id="t1" style="width: 400px; height:40px;" ></label><br/>
<div style="z-index: 1; left: 420px; top: 160px; position: absolute; margin-top: 0px"> <button onclick="validateURL(document.getElementById('t1').value)";> Fire me </button>
</div>
</form>
</body>
</html>
UPDATE
<html>
<head>
<title>ThenWat</title>
<script>#Vicky: above regex does not filter:
function validateURL($URL) {
var str=$URL;;
var n=str.match(/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g);
document.getElementById("demo").innerHTML=n;
//alert("correct or incorrect as per validation"); how to do this?
}
</script>
</head>
<body style="height: 560px">
<form>
<label>Enter URL: <input type="text" value="http://www.paulgraham.com/herd.html" name="sent" id="t1" style="width: 400px; height:40px;" ></label><br/>
<div style="z-index: 1; left: 420px; top: 160px; position: absolute; margin-top: 0px"> <button onclick="validateURL(document.getElementById('t1').value)";> Fire me </button>
</div>
</form>
</body>
</html>
You can use $pattern1.test($URL) or $pattern1.match($URL)instead of using preg_match($pattern_1, $URL)
Try this:
function validateURL($URL) {
alert($URL);
$pattern_1 = /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
$pattern_2 = /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
if($pattern_1.test($URL) || $pattern_2.test($URL)){
alert("correct");
return true;
} else{
alert("Incorrect");
return false;
}
}
var str="The rain in SPAIN stays mainly in the plain";
var n=str.match(/ain/g);
To match string with regular expression in javascript you need to use match(). Check http://www.w3schools.com/jsref/jsref_match.asp
regexp for URL : /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
Update:
function myFunction(){
var str="http://www.google.com";
var regexp = /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/g;
if(str.match(regexp)){
alert("okay");
}else{
alert("not okay");
}
}
regular expression library : https://github.com/javaquery/regexp/blob/master/regexp-0.0.1.js
The problem for your is your regular expression
i have a pretty good one i normally use like this:
[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?
It checks first if something before the first . (ex. testing in testing.mywebsite.com) then checks mywebsite and last after the last dot it even checks the ending

Categories

Resources