javascript input.focus() is not working in firefox 23 - javascript

I am using this code..
Error is showing but focus is not working in firefox. As this code is working in IE, i can't say this code is completely wrong.
<form name="frm" action="search.php" method="post">
<input type="text" name="search" onblur="return check();"/>
<input type="submit" name="submit" />
<strong id="err"></strong>
</form>
I am using this string in external javascript.
This code is in valid.js
function check()
{
var item=frm.search;
var errr=document.getElementById('err');
if(item.value.length<3)
{
item.focus();
errr.innerHTML="Entered String is very short";
return false;
}
}
Please reply me as soon as possible.

try this one
function check()
{
var item = document.forms['frm'].elements['search'];
var errr=document.getElementById('err');
if(item.value.length<3)
{
errr.innerHTML="Entered String is very short";
setTimeout(function() {
item.focus()
}, 10);
return false;
}
}
demo jsfiddle http://jsfiddle.net/ff4vW/

Its good if you use document.getElementById()
But if you are using name
Then you should use
var item = document.forms['frm'].elements['search'];

var item = document.getElementsByName('search')[0];

Related

Js script crashing entire element

I am making a site on google sites.
I have a button made by code that detects if you put a certain value into an input box, it should then load another site. But when I enter that correct value, the object crashes.
I've tried a lot of different things, but nothing works.
<form name="form1" method="GET">
<input name="codebox1" type="text" />
<input name="button1" type="submit" value="Check Code" onClick="return testResults(this.form)"/>
</form>
<script>
function testResults (form) {
if (form.codebox1.value == "Doovhhlqjhbh") {
window.location = 'https://sites.google.com/view/the-mbd-project/There-are-secrets-to-be-discovered';
window.alert("Correct Code. Connecting...");
}
else {
window.alert("Wrong Code, try again!");
}
return false;
};
</script>
window.location = string; is wrong . You should use this to change the browser address. Also, alert must be executed before switching the page
change your function to this:
function testResults(form) {
if (form.codebox1.value == "Doovhhlqjhbh") {
window.alert("Correct Code. Connecting...");
setTimeout(() => {
window.location.href = 'https://sites.google.com/view/the-mbd-project/There-are-secrets-to-be-discovered';
}, 0);
}
else { window.alert("Wrong Code, try again!"); }
return false;
}

Regex always returning either always true or always false regardless of valid test value

I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.
HTML:
<form name="newform" action="Create.php" onsubmit="return validateForm()" method="POST" >
Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
JavaScript:
<script type="text/javascript">
function validateForm(){
var CodePattern = new RegExp(/\b\d{5}\b/);
if(CodePattern.test(document.forms["newform"]["code"].value) == true)
{
return true;
}
else
{
return false;
}
}
function CodeStyleRefresh(){
document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>
Some other ways I have tried to specify the expression:
var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';
This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.
UPDATE:
I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:
function validateForm(event)
{
console.log("Im running the script!");
console.log(event.target.querySelector("[name=code]").value);
var CodePattern = new RegExp(/\b\d{5}\b/);
var codeVal = event.target.querySelector("[name=code]").value;
if(CodePattern.test(codeVal) == true)
{
alert("Expression Passed!");
}
else
{
alert("Expression Failed!");
return false;
}
}
My HTML is now:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
Still this expression is only hitting the failed state and alerts expression failed.
If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!
Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?
Try a context aware piece of code, update your html to:
<form name="newform" onsubmit="return validateForm(event)" method="POST">
Code
<input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
<button type="submit" id="submit" name="submit">Create</button>
</form>
And your javascript:
function validateForm(event){
var myRegex = new RegExp(/\b\d{5}\b/);
//event.target holds the node element that triggered the function in our case, the Form itself
var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event
return myRegex.test(myValue) //return true if it passed, false if not
}
Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
var CodePattern = /\b\d{5}\b/;
// comment below line after testing
evt.preventDefault();
if(CodePattern.test(codeVal) == true)
{
console.log("Expression Passed!");
return true;
}
else
{
console.log("Expression Failed!");
return false;
}
}
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="abc 12345 foo bar" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.
I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:
function validateForm(frm, evt)
{
var codeVal = frm.code.value;
console.log("Code Value: " + String(codeVal));
// comment below line after testing
evt.preventDefault();
var lenPass = false;
var strlen = codeVal.length;
if(strlen == 5)
{
lenPass = true;
}
if(lenPass)
{
var c1 = Number.isNaN(Number(codeVal.charAt(0)));
var c2 = Number.isNaN(Number(codeVal.charAt(1)));
var c3 = Number.isNaN(Number(codeVal.charAt(2)));
var c4 = Number.isNaN(Number(codeVal.charAt(3)));
var c5 = Number.isNaN(Number(codeVal.charAt(4)));
console.log(c1);
console.log(c2);
console.log(c3);
console.log(c4);
console.log(c5);
var pass = true;
if(c1)
{
pass = false;
}
if(c2)
{
pass = false;
}
if(c3)
{
pass = false;
}
if(c4)
{
pass = false;
}
if(c5)
{
pass = false;
}
if(pass)
{
alert("Expression Stage 2 Passed!");
return true;
}
else
{
alert("Expression Stage 2 Failed!");
return false;
}
}
else
{
alert("Expression Stage 1 Failed!");
return false;
}
}
<html>
<head>
</head>
<body>
<form name="newform" onsubmit="return validateForm(this, event)" method="POST">
Code <br/><br/>
<input id="code" type="text" value="" name="code" />
<input type="submit" id="submit" name="submit" value="Create" />
</form>
</body>
</html>

enable buttons in javascript/jquery based on regex match

I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>

Using javascript for checking forms

here is my code:
<script>
function check(){
var error = '';
var name = document.forms['form1'].name.value;
var age = document.forms['form1'].age.value;
var checkname = new RegExp("^[a-zA-Z]{3,}$");
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
if (!checkname.test(name)) error+= 'Blad w nameniu\n';
if (!checkage.test(age)) error+= 'Blad w ageu\n';
if (error == '')
return true;
else {
alert(error);
return false;
}
}
</script>
<form name="form1">
<p>Name: <input type="text" name="name"></p>
<p>Age: <input type="text" name="age"></p>
<button type="button" onclick="check()">Send</button>
</form>
I have no idea why the given code simply doesn't work. There is no action at all. I have tried to change <button> to <input type="sumbit"> and <form onSubmit="check()"> but had no luck.
Fiddle
The problem is the regular expression for checkage
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
this needs to be
var checkage = new RegExp("^[1-9]{1}[0-9]{1}$");
And you can use firebug for firefox ( is a free add-on that helps you a lot).
Have a good day.
The problem of your code is the checkage regular expression. Instead of this :
var checkage = new RegExp("^[1-9]{1}+[0-9]{1}$");
You could try :
var checkage = new RegExp("/(^[1-9]?[0-9]{1}$|^100$)/");
But IMHO, regex is not the good way to validate the age. You should just write a simple function which check if the number is in between 0 - 100 range
Hope this helps !

keypress not working in chrome or firefox

function firstname()
{
var x=document.forms["frm"]["fname"].value;
if(x=="")
{
document.getElementById("checkfname").value = " First Name required";
return false;
}
else
{
document.getElementById("checkfname").value = "";
return true;
}
}
<html>
<body>
<form method="post" name="frm">
<input type="text" name="fname" onkeypress="firstname()" onkeydown="firstname()" onkeyup="firstname()"/>
<input name="checkfname"/>
</body>
</html>
cant get the function run at all in chrome or Firefox?? it isn't firing up. Any help pls?
First of all make sure you have javascript code inside the script tag and then
you are using document.getElementById("checkfname") but you haven't give checkfname as Id of any element. So it's gonna be undefined element so change it like this
<input id="checkfname"/>
and then try your code.
JsFiddle

Categories

Resources