JavaScript Replace Method for multiple textboxes - javascript

Can anyone please tell me how I can use the replace method to replace a character if it occures in more than one textbox without having to write separate function for each textbox.
The code below is the basic way to use the replace method but it only allows for one textbox.
I'm sure I need a loop in there but I'm not sure how to use that without affecting the replace method.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function stringReplace(form) {
var replaceStr = form.textfield1.value
var pattern = /\'/g;
form.textfield1.value = replaceStr.replace(pattern, "''");
}
</script>
</head>
<body>
<form name="form1" method="post" action="JStest_redirect.asp">
<p>fname:
<input type="text" name="textfield1" size="20">
</p>
<p>lname:
<input type="text" name="textfield2" size="20">
</p>
<p>
<input onclick="return stringReplace(form)" type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>

You can do this:
function stringReplace(form) {
var $inputs = $(form).find('input:text');
var pattern = /\'/g;
$inputs.each(function () {
this.value = this.value.replace(pattern, "''");
});
return false; // Prevent the form from being submitted
}
This would find all the input type text within the form and replace their values.

If you wish to do it without jquery, you can use the getElementsByTagName() method.
function stringReplace(form) {
var pattern = /\'/g;
var inputs = form.getElementsByTagName("input");
var input;
for (var i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.type = 'text') {
var replaceStr = input.value;
input.value = replaceStr.replace(pattern, "''");
}
}
return false;
}

You seem to want
function stringReplace(form) {
$('input[type=text]').val(function(_, v) {
return v.replace(/\'/g, "''");
});
return false;
}
I added a return false at the end to prevent the form to be submitted on click. You probably want to have a separate button in your case.

I believe that fisrt you have to take all the values
function GetValue(){
var Contain = "";
$("#form1 :text").each(function(){
//add replace code here
});
}

You can add onchange function to all of you text input
function stringReplace(textField) {
var replaceStr = this.value
var pattern = /\'/g;
this.value = replaceStr.replace(pattern, "''");
}
and than you add
<input type="text" name="textfield1" size="20" onchange="stringReplace(this);">

Related

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

How to auto add a hyphen in user input using Javascript?

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx
Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?
Pretty sure there is! Just gotta check how many characters the inputted string has, and if it's 5, add a hyphen to the string :)
var input = document.getElementById("ELEMENT-ID");
input.addEventListener("input", function() {
if(input.value.length === 5) {
input.value += "-";
}
}
Try the following.
function add_hyphen() {
var input = document.getElementById("myinput");
var str = input.value;
str = str.replace("-","");
if (str.length > 5) {
str = str.substring(0,5) + "-" + str.substring(5);
}
input.value = str
}
<input type="text" id="myinput" value="a" OnInput="add_hyphen()"></input>
Anna,
The best way to do it would be to use a regular expression. The one you'll need is:
^[0-9]{5}(?:-[0-9]{4})?$
You would ten use something like:
function IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('Invalid ZipCode');
}
}
In your HTML call it like this:
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />
For more on Regular Expressions this is a good article:
Regular Expressions on Mozilla Developers Network
You can try using simple javascript function as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script>
function FN_HYPEN(){
var input = document.getElementById("USER");
if(input.value.length === 5) {
input.value += "-";
}
}
</script>
</head>
<body>
<INPUT ID="USER" TYPE="TEXT" onKeypress="FN_HYPEN();"/>
</body>
</html>

Censoring / Highlighting using JavaScript

I'm trying to create a small sample application for highlighting / censoring of a textarea using JavaScript. To start with I'm just trying to replace the letters, though once that is solved my plan was to use mark.js to mark censored words. Right now when I run my application I'm getting Uncaught TypeError: Cannot Read property 'value' of null on line 21.
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('comments');
var badWords = ["x", "y", "z"];
var censored = censore(commentContent.value, badWords);
}
function censore(string, filters) {
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea id="pesho" name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('pesho');
var badWords = ["crap", "fuck", "cunt"];
console.log(commentContent.value)
commentContent.value =censore(commentContent.value, badWords);
}
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
As some of the other guys before me mentioned, you were not targeting the id of the text area but the name attribute, beside that for the function to make actual changes on the view you must change the targeted element value (see the modified example)

Validate that Name field contains text only

I want that Name field should contain text only.
<html>
<head></head>
<body>
<form name="form1">
Name <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Can anyone tell me how can I do so using either HTML or Javascript.
Use this regex in your Javascript: /^[a-z]+$/i
WORKING DEMO
Javascript:
var submit = document.getElementById("submit");
submit.addEventListener("click", checkInput, false);
function checkInput(e){
e.preventDefault();
var pattern = /^[a-z]+$/i;
alert(pattern.test(document.getElementById('text').value));
}
You can test whether there's "anything left" after removing alpha characters.
<html>
<body>
<form name="form1" onsubmit="return checkform();">
Name<input type="text" name="fname" id="fname">
<input type="submit" value="Submit">
</form>
<script>
function checkform(){
var fname=document.getElementById('fname').value;
if (fname.replace(/\w/g,'')!=''||fname==''){
alert('invalid firstname!');
return false;
}
return true;
}
</script>
</body>
</html>
try this:
<script type="text/javascript">
function validate(){
var allowedChars="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var n=form1.fname.value;
for(var i=0;i<n.length;i++){
if(allowedChars.indexOf(n.charAt(i))==-1){
return false; // contains other char
}
}
return true; //valid name
}
Try regular expressions like
var match_text = /[a-zA-Z]/;
try this var regx = /^[A-Za-z][-a-zA-Z ]+$/;
function validate_form();
{
var regx = /^[A-Za-z][-a-zA-Z ]+$/;
var fname = document.getElementById('fname').value;
if(fname=="")
{
alert("Name is Blank");
return false;
}
else if(!regx.test(fname))
{
alert("name must contains character only");
return false;
}
else
{
return true;
}
}
Pattern checking of the textbox must be done with Javascript or Jquery like in other answers BUT if you want to use HTML5, you can directly write :
<input type="text" name="fname" id="fname" pattern="[A-Za-z]+" />
(See 'pattern' attribute in HTML5 if you're interested).
You can call this function to validate input field containing only text--
function validate()
{
str = document.form1.fname.value;
var patt = new RegExp("^[a-zA-Z ]*$");
var res = patt.test(str);
if(!res)
{
alert("do not match!");
return false;
}
}

copy text from one textbox to another based on a condition

I am working on javascript.
Consider two textboxes tb1 and tb2 respectively
The value present in tb1 should be copied in tb2 based on a condition. If the condition is true nothing needs to be copied. If the condition is false the value in tb1 should also be initialised to tb2. Is it possible..
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div>
<span>tb1:</span>
<input id="tb1" type="text" value="TextBox Value 1"/>
</div>
<div>
<span>tb2:</span>
<input id="tb2" type="text" value="TextBox Value 2"/>
</div>
<input type="button" onclick="exchange()" value="Exchange">
<script type="text/javascript">
function exchange(){
var tb1 = document.getElementById('tb1');
var tb2 = document.getElementById('tb2');
var condition = function(){
return true;
};
if(condition()){
var buf = tb1.value;
tb1.value = tb2.value;
tb2.value = buf;
}
}
</script>
</body>
</html>
Here's a function that can do what you need:
function compareAndCopy() {
var tb1 = document.getElementById("tb1");
var tb2 = document.getElementById("tb2");
if (tb1.value == "hey") {
tb2.value = tb1.value;
} else {
alert("No match");
}
}
//Add a handler
document.getElementById("tb1").onblur = compareAndCopy;
It is currently checking if tb1 equals hey on blur.
Working demo: http://jsfiddle.net/4L5pE/
yes, this is possible. You need to define when you want it to happen. onkeypress, or onblur of first text box you can call a function that validates your condition and then copies the values.
tb1.onblur(function(){ if(condition) tb2.value = tb1.value }
the code above will not work, its just a pseudo.

Categories

Resources