I'm trying to take the input string and verify whether an image exists on the URL.
When I click the 'Check' button, the intended result is to validate whether the input value is a regex match. If it is or is not, display an appropriate result.
JS
checkImage.addEventListener("click", function () {
let url = document.getElementById("inputUrl").value;
// console.log(url);
if (typeof url !== "string") result.textContent = "This is not an image";
return url.match(/\.(jpg|jpeg|gif|png)$/) != null;
result.textContent;
});
checkImage.addEventListener("click", function () {
let url = document.getElementById("inputUrl").value;
// console.log(url);
if (typeof url !== "string") result.textContent = "This is not an image";
return url.match(/\.(jpg|jpeg|gif|png)$/) != null;
result.textContent;
});
<form action="">
<input type="text" id="inputUrl" placeholder="url of image">
<button type="button" id="checkImage">Check</button>
</form>
<h3 id="result">?</h3>
You're returning from the event handler before anything is put in the result div.
A few other notes.
using regex.test() is the appropriate method for testing if a string matches a pattern. The match method you used, although it will work, is intended for extracting parts of a string.
Your url variable will always be a string as the value of an input, so checking that is unnecessary.
var checkImage = document.getElementById("checkImage");
var result = document.getElementById("result");
checkImage.addEventListener("click", function () {
let url = document.getElementById("inputUrl").value;
var is_image = /\.(jpg|jpeg|gif|png)$/.test(url);
result.textContent = is_image ? 'valid image' : 'invalid';
});
<form action="">
<input type="text" id="inputUrl" placeholder="url of image">
<button type="button" id="checkImage">Check</button>
</form>
<h3 id="result">?</h3>
You always return before you set the textContent.
It's not clear what the isImage does, but it seems redundant because you've already checked the URL in the event handler.
Maybe this is more like what you intended:
var result = document.getElementById("result");
var checkImage = document.getElementById("checkImage");
checkImage.addEventListener("click", function () {
let url = document.getElementById("inputUrl").value;
console.log(url, typeof url);
if (typeof url !== "string") result.textContent = "This is not an image";
if (url.match(/\.(jpg|jpeg|gif|png)$/) != null) {
result.textContent = "Yes";
}
else
{
result.textContent = "No";
}
});
<form action="">
<input type="text" id="inputUrl" placeholder="url of image">
<button type="button" id="checkImage">Check</button>
</form>
<h3 id="result">?</h3>
N.B. Note that this approach simply checks whether the URL ends with a file extension used by popular image formats. It does not check whether the resource returned by that URL actually is an image (and may also exclude some URLs which return image data but have a different URL format).
i guess you are returning before calling this result.textContent = isImage(url); whatever that does
Related
I have a form that takes the users input and concatenated that to a url (written in function). How do I check to see if the users value is empty and have an alert appear right below the form that says "Please enter a valid store URL". With out having to re write my entire function! Help!
Input form
<form id="url">
<input type="text" name="urlName">
<button onclick="return myFunction()">Try it</button>
</form>
Javscript Function
document.getElementById("url").addEventListener("submit", myFunction);
function myFunction() {
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
Check empty string I have not working
function valInput() {
if (input.value.length === 0){
alert("need valid store URL")
}
}
In myFunction you can simple add this code after creating a new instance of FormData:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You call the myFunction twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction.
And in HTML you don't need button. You can add input:submit which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>
You can add an onBlur handler to the input.
function validate(val) {
if(val.trim() === "") {
alert("Field is required");
}
}
<input type="text" name="urlName" onblur="validate(this.value)">
I'm willing to use two textfields to pass on values via url.
Here are my textfields:
<h3 class="title1">Email</h3>
<input type="text" id="myTextField1" />
<br/><br/>
<h3 class="title2">Secret</h3>
<input type="text" id="myTextField2" />
<br/><br/>
There's a link below them:
<a id="myLink" href="index2.php"></a>
Then there's a function I use, which should create something like:
index2.php?email=value1&secret=value2
However what I am getting is:
index2.php?email=value1, secret=value1&email=value2, secret=value2
This is the function I use:
document.querySelector('#myBtn').addEventListener('click', function change() {
function isInvalid(input) {
return input.value.length == 0;
}
var inputs = [...document.querySelectorAll('[id^="myTextField"]')];
var anchor = document.getElementById('myLink');
var querystring = inputs.map((input) => {
// Remove all leading non-digits to get the number //ex bladiebla1 = 1
var number = input.id.replace( /^\D+/g, '');
var titles = [...document.querySelectorAll('.title'+ number)];
titles.forEach((title) => title.innerHTML = input.value);
return `email=${input.value}`+` secret=${input.value}`;
});
anchor.href = `index2.php?${querystring.join('&')}`;
document.getElementById('result').innerHTML = querystring;
});
I realize that it is wrong and I get why this doesn't return what I want however I do not know how to fix this..
Could anybody tweek my code and point me in the right direction?
You're overcomplicating things here a bit.
You have the inputs in the inputs variable. If they had a name attribute in the html you can simply map over them and get the values out.
You don't really need the bit where you parse the number from the ID.
document.querySelector('#myBtn').addEventListener('click', function change() {
function isInvalid(input) {
return input.value.length == 0;
}
var inputs = [...document.querySelectorAll('[id^="myTextField"]')];
var anchor = document.getElementById('myLink');
var querystring = inputs.map((input) => {
return `${input.name}=${input.value}`;
});
anchor.href = `index2.php?${querystring.join('&')}`;
document.getElementById('result').innerHTML = querystring.join('&');
});
<h3 class="title1">Email</h3>
<input type="text" name="email" id="myTextField1" />
<br/><br/>
<h3 class="title2">Secret</h3>
<input type="text" name="secret" id="myTextField2" />
<br/><br/>
<button id=myBtn>Run the function</button>
<a id=myLink>Target Link</a>
<h3>Results:</h3>
<div id=result></div>
You iterate through each input and set email and secret for each of two inputs. Just add check for id. Something like return number === 1 ? email=${input.value} : &secret=${input.value};
i am building a search function which use many filters. i decide to use the get method instead of post (different reasons). Problem is, when using many filters the querystring gets very long, especially when i use filter with same name so i get
myurl.com?filter1[]=val1&filter1[]=val2&filter2=val
To get better control and to prevent 0 values i tried serializeArray:
var array = {};
jQuery.each(jQuery('form').serializeArray(), function(index,val) {
if (val.value != 0 )
array[value.name] = val.value;
});
But this way it overrides the first filter1 with the last value of filter1, so multiple values doesn´t work. And then i have the "problem" to create the querystring. I am not a javascript prof. so i need a little help here.
What can i do, so i get a querystring which looks like:
myurl.com?filter1=val1|val2&filter2=val and so on
The HTML are "normal" input fields
<input type="checkbox" name="filter1[]" />
<input type="text" name="filter2" />
Thank you in advance
ruven
How about this (working demo):
<form action="search.html">
<input type="text" value="val1" name="filter1" />
<input type="text" value="val2" name="filter1" />
<input type="text" value="val" name="filter2" />
<input type="submit" value="search" name="cmdSearch" />
</form>
<script>
// don't do anything until document is ready
$(function() {
// register to form submit event
$('form').submit(function(e){
// stop the form from doing its default action (submit-GET)
e.preventDefault();
// initialise url
var url = '';
// keep track of previously enumerated field
var prev = '';
// iterate all fields in the form except the submit button(s)
$('input:not([type="submit"])', $(this)).each(function(){
// get the name of this field, with null coalesce
var name = $(this).attr('name') || '';
// get the value of this field
var val = $(this).attr('value');
// does this field have the same name as the previous?
if (name.toLowerCase() == prev.toLowerCase()) {
// same name therefore we have already appended the name
// append value separator
url += '|';
}
else {
// different name, track new name
prev = name;
// append parameter separator, parameter name, equals char
url += '&' + name + '=';
}
// append value of this field
url += val;
});
// removing leading ampersand
if (url.length && [0] == '&') {
url = url.substring(1);
}
// insert leading question mark
url = '?' + url;
// insert url from "action" attribute of the form
url = $(this).attr('action') + url;
// display url (delete this line)
alert(url);
// redirect to the new url (simulates the GET)
window.location.href = url;
});
});
</script>
I am learning how to do a query string what html would you use for the following function on the sending and receiving page to see the result of author?
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
I found it at: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
Are they any good query string examples?
I can't quite tell what you are asking but I guess you're looking for a way to test this method and verify its behavior. Here is what I would do, save these contents in an HTML file:
<html>
<body>
<form name="form1">
Key: <input type="text" name="text1" value="author"/>
<input type="button" name="button1" value="Test"/>
</form>
<script>
document.form1.button1.onclick = function() {
alert(getQuerystring(document.form1.text1.value));
}
function getQuerystring(key, default_) {
// your code here...
}
</script>
</body>
</html>
Now you can open your HTML page in a web browser and add a query string like "?author=me&foo=bar". For example, if your file is saved in "C:\tmp\example.html" then your URL should look like this:
file:///c:/tmp/example.html?author=me&foo=bar
The page will show a text field (which says "author" by default) and a button and when you press the button the page will show a popup with the result of running the function with the value you put in the text field. With my example query string, the key "author" should alert "me" and the key "foo" should alert "bar".
http://www.example.com?variable=string&var2=ok&var3=str3
is an example of a query string
<script>
var_this = getQuerystring(var2);
if(var_this == "ok"){
//do this
}else{
// do this
}
</script>
function getQuerystringParameter(name, _default) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return (match && decodeURIComponent(match[1].replace(/\+/g, ' ')) || _default;
}
I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.
This is the existing form
<form id = "submit" method="post">
<label for="link_website_url">Create a short url</label>
<input id="link_website_url" name="link" size="30" type="text" />
<input class="go" name="commit" type="submit" value="Go!" /></form>
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
return false; //error, so cancel this submit
}
});
If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:
var checkFailed = false;
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
$('#error_link_web_url').remove();
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
checkFailed = true;
}
/*Other checks...*/
if(checkFailed){
return false; //cancel submit
}
});
$('#submit').submit(function(){
var url = $('#link_website_url').value();
var val = <do your processing here>;
$('#link_website_url').value(val);
return false;
});