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;
}
Related
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
I'm creating a web front for a database using HTML, CSS, JavaScript and PHP for my uni coursework. I've only got so far as HTML and JavaScript form validation before I've run into this weird problem.
In my HTML, I link the JavaScript as follows:
<script type="text/javascript" src="dbicw2.js"></script>
Correct file name, I've checked.
Next, I have a form which takes a user's search. It upon submitting runs my JavaScript function, and its action is a PHP file. The code is as follows:
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
Again, correct PHP filename and JS function name.
Now, my JavaScript function seems to always return True, regardless of what happens. Currently, my JS looks like:
function validate(form)
{
alert("Hi")
for (var field in form.elements) { //For elements in form
field+="" //Incase it is undefined
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
Not even the alert message at the top runs. The form just goes through and PHP is loaded, regardless of the JS. The script neither works in Edge.
This is baffling because my code is a near clone of my professor's example, which works.
What is causing the Javascript to not be run and the PHP action done?
Edit: my professor's example code, which works:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>(prof name)</title>
<LINK REL='stylesheet' TYPE='text/css' HREF='dbicw.css'>
<script type="text/javascript" src="dbicw.js"></script>
</head>
<body>
<h1>Search for a Movie by Title</h1>
<form action="search_movie_example.php" onSubmit="return validate(this)">
Movie title:<br>
<input type="text" name="title">
<br>
<br>
<input type="submit" value="Search">
</form>
</body>
</html>
JavaScript:
function validate(form)
{
var ok=1
var msg=""
for (var i = 0; i < form.length; i++) {
if (form.elements[i].value.trim() == "") {
msg += "'" + form.elements[i].name + "' is void. "
ok=0
}
}
if (ok == 0) {
alert(msg)
return false
}
else {
return true
}
}
I think I found a mistake (hopefully THE mistake) in your code. It's really simple, but very common.
You iterate over your form elements using for (var field in form.elements), but this will iterate over the index values of the form elements, rather than over the actual elements. Change in to of to iterate over the actual values instead.
Example:
let arr = ['foo', 'bar', 'cat'];
for (let word in arr) {
console.log(word); // prints 0, 1, 2
}
for (let word of arr) {
console.log(word); // prints foo, bar, cat
}
Try this:
function validate(form) {
event.preventDefault();
alert("Hi")
for (var field of [...form.querySelectorAll('input:not([type="submit"])')]) { //For elements in form
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
}
}
}
<form action="dbicw2.php" onsubmit="validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
I added an event.preventDefault() so the page wouldn't be redirected in the live example, and changed the in to of while also altering the statement that "fetches" the input elements. The of simply allows you to iterate through the array, and the actual selector just gets all the input elements that are not of the type submit.
If you only want to alter your code to make it work, then try this:
function validate(form) {
alert("Hi")
for (var field of [...form.elements]) { //For elements in form
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
I again changed the in to of, and added a spread operator to convert the HTMLFormControlsCollection to an array.
Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online
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'm trying to get the word wrapped line breaks from a textarea without having make any server calls. This answer gets me 90% of the way there. The problem is that the page is reloaded inside of the iframe each time the submit button is clicked. Here's the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<script type="text/javascript">
function getURLParameter(qs, name) {
var pattern = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(pattern);
var res = regex.exec(qs);
if (res == null)
return "";
else
return res[1];
}
function getHardWrappedText() {
var frm_url = document.getElementById('frame').contentDocument.URL;
var text = unescape(getURLParameter(document.getElementById('frame').contentDocument.URL, 'text')).replace(/\+/g, ' ');
return text;
}
function onIFrameLoad() {
var text = getHardWrappedText();
console.log(text);
}
window.onload = function() {
console.log("loading")
};
</script>
<form name="form" method="get" target="frame">
<textarea id="text" name="text" cols=5 wrap="hard">a b c d e f</textarea>
<input type="submit">
</form>
<iframe id="frame" name="frame" onload="onIFrameLoad()" style="display:none;"></iframe>
</body>
</html>
Clicking on the submit button gives the output:
loading
a b c d e
f
Is there a way to prevent the iframe from reloading the page?
You have to return a false to the onsubmit event of the form.
<form name="form" method="get" target="frame" onsubmit="onIFrameLoad">
If it is based on some condition that you do not want to load
function onIFrameLoad() {
var text = getHardWrappedText();
console.log(text);
if(text.indexOf('\n')<0) return false;
}
Am just putting a random thing at text.indexOf('\n')<0, you can have anything that makes sense or always return false (which looks unlikely)