I have a text input search field. I'd like to add an escape backslash to any colon entered by the user. This is what I have right now:
<form role="form" action="..." method="get">
<div>
<input id="input" type="text" name="q">
<button id="search_button" type="submit">Go!</button>
</span>
</div>
</form>
<script type="text/javascript">
document.getElementById("search_button").addEventListener('click', function() {
let text = document.getElementById('input').value;
let regex = /:/gi;
let new_text = text.replaceAll(regex, "\:");
});
</script>
It doesn't seem to work, though: the string sent to the 'q' parameter has the colon without the escape character. What am I missing?
Even when fixing the replacement with the additional backslash, your code still wont work because you also need to change the value of the form field with its new value, as follows "new code":
<form role = "form" action="..." method="get">
<div>
<input id="input" type="text" name="q">
<button id="search_button" type="submit">Go!</button>
</span>
</div>
</form>
<script type="text/javascript">
document.getElementById("search_button").addEventListener('click', function () {
let text = document.getElementById('input').value;
let regex = /:/gi;
let new_text = text.replaceAll(regex, "\\:"); // fix
document.getElementById('input').value = new_text; // new code
});
</script>
\ is a special character in string used in escape sequences. If you want to literally add a \ to a string you have to escape it as well.
let new_text = text.replaceAll(regex, "\\:");
Because the backslash have a special meaning you have to escape this character.
You can easily do it by \\:
<form role="form" action="..." method="get">
<div>
<input id="input" type="text" name="q">
<button id="search_button" type="submit">Go!</button>
</span>
</div>
</form>
<script type="text/javascript">
document.getElementById("search_button").addEventListener('click', function() {
let text = document.getElementById('input').value;
let regex = /:/gi;
let new_text = text.replaceAll(regex, "\\:");
document.getElementById('input').value = new_text; // new code
});
</script>
Related
The goal is to replace some characters directly when written in the form input, not after submitting the form. Also, I would like to change the contrast of the replacing character to be kind of grey/less visible.
I came up with something like that (but not working infortunately):
<form action="" method="post">
<input type="text" name="test_input" id="test_input" onkeypress="myFunction()" required>
<input type="submit" value="Subscribe!">
</form>
<script>
function myFunction() {
let str = document.getElementById("test_input").innerHTML;
let res = str.replace(/a/g, "b");
document.getElementById("test_input").innerHTML = res;
}
</script>
You have some mistakes in your code. Check out corrected code.
You need to correct your pattern.
<form action="" method="post">
<input type="text" name="test_input" id="test_input" onkeyup="myFunction()" required>
<input type="submit" value="Subscribe!">
</form>
<script>
function myFunction() {
let str = document.getElementById("test_input").value;
let res = str.replace(/a/g, "b");
console.log(res)
document.getElementById("test_input").value = res;
}
</script>
Try a cleaner solution that uses regular expressions:
<input type="text" onkeyup="this.value=this.value.replace(/[Search Expression]/flag,'New String');"/>
This solution prevents the user from typing a value outside the pattern established by the regex.
Example:
To remove all the numbers from "name" field:
<input type="text" onkeyup="this.value=this.value.replace(/[\d]/g, '');">
I'm trying to make sure the input in a particular field is just an 11 digit number, however my if condition does not seem to be working:
Javascript:
<script>
function check() {
var x = document.forms["myform"]["mobile"].value;
if (!/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
}
</script>
And the HTML is:
<form id="myform" onsubmit="check();" >
<input class="input" type="text" name="mobile" required="required"
oninvalid="this.setCustomValidity('Number is empty')" oninput="setCustomValidity('')" />
</form>
Please help!
You can try maxlength and type attribute of input field:
<input class="input" type="text" name="mobile" maxlength="11" type="number" required="required"/>
If it satisfy your case then you don't need to call javascript function.
Your regular expression is working just fine. I think the error lies in the "if" condition. Try changing
if (!/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
to this
if (/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
As you can see I just took off the negation in the expression.
Note: Assuming that the "mobilerror.html" is shown when the user didn't type the 11 digit as expected.
Try this
function check() {
var x = document.forms["myform"]["mobile"].value;
var pattern = new RegExp("^1?([1-9])(\\d{10})");
if (pattern.test(x)) {
myform.action="gender.html";
} else {
myform.action="mobilerror.html"
}
}
^1?([1-9]) checks if the first number is not zero, so that the input value is numerically a 11-digit number. If you don't want it you can remove it.
This help you :
use type 'number':
<input type="number" id="number" class="input">
and test number digits is 11 or not with :
var patt = /.{11}/;
Example :
<html>
<head>
<style>
</style>
</head>
<body>
<form id="myform" onsubmit="check()" >
<input id="number" class="input" type="number">
<button type="submit">Submit</button>
</form>
<script>
var patt = /.{11}/;
function check(){
var num = document.getElementById("number").value;
var frm = document.getElementById("myform");
if(patt.test(num))
frm.action ="mobilerror.html"
else
frm.action = "gender.html";
}
</script>
</body>
</html>
I'm looking for code that validates the Name and Email input's on <Form onsubmit="return validate();">
I want that username has only A-Z,a-z and must have an underscore_, email should have an #. How can i do it with jQuery?
Form(example):
<html>
<head>
<title>TEST</title>
</head>
<body>
<form action="..." method="POST" onSubmit="return Check()" >
<input type="text" id="name" placeholder="Please enter your Name. (Must have underscore)" required>
<input type="text" id="email" placeholder="E-Mail">
<input type="submit" value="submit">
</form>
</body>
</html>
EDIT I've tried:
<script type="text/javascript">
jQuery(document).ready(function($){
$('[name="submit"]').click(function(e){
var name = document.getElementById("name").value;
if(re = /[a-zA-Z]*_[a-zA-Z]*/;) {
$(".name").addClass("error");
return false;
} else {
$(".name").removeClass("error");
$(".name").addClass("success");
return true;
}
});
});
Thanks!
For a valid email address:
Validate email address in JavaScript?
For your username is the same but your regex should be something like this:
re = /^[a-zA-Z]*_[a-zA-Z]*$/; //this always needs an underscore to be valid.
Just in case, this is the regex to accept anything az AZ and _ and nothing, it depends on your requirements:
re = /^[a-zA-Z_]*$/;
re = /^[a-zA-Z_]{3,}$/; //3 or more chars
To test your regex:
re = /^[a-zA-Z_]*$/;
return re.test('any_string_to_test'); //it returns true if your string is valid
Using regex with jquery:
Pass a string to RegExp or create a regex using the // syntax call
regex.test(string) not string.test(regex)
In your code:
$(".name").on('keyup', function(e)
{
var name = $(this).val();
if(new RegExp(/^[a-zA-Z_]+$/i).test(name)) // or with quotes -> new RegExp("^[a-zA-Z_]+$", 'i')
$(this).addClass("error");
else
$(this).switchClass("error", "success", 1000, "easeInOutQuad");
e.preventDefault();
e.stopPropagation(); // to avoid sending form when syntax is wrong
});
And for email input, the following regex can do the job :
/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
Or..
To put a little bit of modernity, you can use html5 email field type
<input type="email" id="email">
Now using the advanced feature of HTML5 it's eaiser, you can simply do the validation as follow:
<form action="" method="">
<!-- Name containing only letters or _ -->
Name: <input type="text" name="name" pattern="[a-zA-Z][[A-Za-z_]+" />
<!-- using type email, will validate the email format for you-->
Email: <input type="email" id="email" />
<input type="submit" value="Submit">
</form>
Check HERE for more form validation features of HTML5.
#Polak i tried so, if i understand what you mean :x Sorry i'm new with javascript.
<script type="text/javascript">
jQuery(document).ready(function($){
$('[name="submit"]').click(function(e){
var name = document.getElementById("display_name").value;
re = /[a-zA-Z]*_[a-zA-Z]*/;
if (re.test(name) {
//Things to do when the entry is valid.
$(".NameCheck").removeClass("name_error");
$(".NameCheck").addClass("name_success");
return true;
} else {
//Things to do when the user name is not valid.
$(".NameCheck").addClass("name_error");
return false;
});
});
});
I have a form in which there is one text field and ine submit button.on click of submit button,it goes to next PHP page.The user can enter text in the text field.The text field can contain n number of text string separated by space.like a user enters text as
MY name is peter
I want text to change as MY-name-is-peter in url.
when user clicks on submit button.the url should become like submit.php?search=MY-name-is-peter
<form action="submit.php" method="get">
<input type="text" name="search" id="search">
<input type="submit" name="submit" value="submit">
</form>
PLease guide on how to add hyphen in the strings in url.
<script>
var handler = function (element) {
element.form.search.value = element.form.search.value.replace(/ /g, '-');
};
</script>
<form action="" method="get">
<input type="text" name="search" id="search" />
<input type="submit" onclick="handler(this);" name="submit" value="submit" />
</form>
str_replace will work or if you want to use regex you can try preg_replace("/[-]/", " ", $yourString)
You should encode URL before submit it:
$('form').submit(function(){
var val = $(this).find('#search').val();
$(this).attr('action','submit.php'+encodeURI(val))
})
Example : http://jsfiddle.net/e3L3a/
I have a form in which there is one text field is provided with a submit button.On clicking submit button,it redirects to second php page from first php page.
index.php
<form action="submit.php" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert()" />
</form
<script type="text/javascript">
function convert()
{
alert("hi");
var str ;
str = document.getElementById("search").value;
document.writeln(str.toLowerCase());
}
</script>
On submitting the form,i want the url to become like submit.php?search=text
I want this text to be in lower case,although if text entered is uppercase.
Please guide me how to make this text lower case,I am using the above script for converting it to lower case.But its not converting the text in lower case in URL.
Please guide me on this..
There was a few errors, you were missing the right angle bracket on </form> and you were trying to write the value rather than setting the field value, try this...
<form action="submit.php" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert();" />
</form>
<script type="text/javascript">
function convert() {
alert("hi");
var str;
var srch=document.getElementById("search");
str = srch.value;
srch.value=str.toLowerCase();
}
</script>
You can do this only using javascript with a few extra stuff:
1) Give your <form> an id
<form action="submit.php" method="get" id="form1">
2) Make your <input> type as button. The reason for this is because we want to make sure the convert() function is executed first, and after that we will submit the form.
<input type="button" value="submit" onclick="convert()" />
3) Finally javascript to:
function convert()
{
alert("hi");
var str ;
str = document.getElementById("search");
str.value = (str.value.toLowerCase());
//get the form id and submit it
var form = document.getElementById("form1");
form.submit();
}
Fiddle
You are use form element so you can get any elements inside form element access by name, Here Our form name is form1 and inside this form inputbox name="search" and access this value by this way, document.form1.search.value.toLowerCase();
Check this Demo jsFiddle
JavaScript
function convert() {
alert("hi");
var str = document.form1.search.value.toLowerCase();
document.writeln(str);
//console.log(str);
}
HTML
<form name="form1" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert();" />
</form >
try like this:
alert("hi");
document.getElementById("search").value = document.getElementById("search").value.toLowerCase();
return true;
Fiddle Live