This question already has an answer here:
This doesn't seem right? Javascript isn't working
(1 answer)
Closed 8 years ago.
I'm trying to make fields required but I want the error to show up next to the field it self not be alert?
You can put validation messages near inputs you wanna validate like
<span class="reqMsg">* First name is required</span>
Of course you need to hide them at first with css
.reqMsg {
color:red;
display:none;
}
Then in your form submit function you can change your relevant code to this
var valid = true;
var firstFocus = null;
for (var i = 0; i < rules.length; i++) {
if (!rules[i][1]) {
valid = false;
var parent = elem(rules[i][0]).parentNode;
parent.children[2].style.display = "inline";
if (firstFocus == null) firstFocus = parent.children[1];
}
}
if (!valid) {
firstFocus.focus();
return false;
}
return true;
You can see that it's not returning false immediately if one field is not valid. It checks all the fields then set a focus to first element of those that are not valid.
FIDDLE
Add span tag next to input tag
<span id="first-name-err"></span>
and change you javascript code as below
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}
var flag = true;
for (var i = 0; i < rules.length; i++) {
alert(rules[i][0]);
if (!rules[i][1]) {
var parent = elem(rules[i][0]).parentNode,
message = 'Please check your ' + (parent.textContent || parent.innerText).replace(/^\s*(.*?)\s*$/, '$1').slice(0, -1).toLowerCase() + '.';
var id = rules[i][0]+'-err';
document.getElementById(rules[i][0]+'-err').innerHTML = message;
flag = false;
}
}
return flag;
};
check this
Related
I am trying to check my user inputted password with a series of if statements and boolean variables within a function. It seems like my if statements are not modifying my boolean variables. Could someone tell me why?
I was trying to use (/[a-zA-z]/).test(pValue.charAt(0))) as a boolean to see if the first character entry was a lower or upper case letter, but that didn't work either.
document.querySelector("#enter").addEventListener("click", validate);
function validate(e) {
var count = false;
var firstChar = false;
var hasNum = false;
var special = false;
var pValue = document.querySelector("#passwrd").value;
var pLength = pValue.length;
console.log(pValue);
console.log(pLength);
if(pLength > 4 && pLength <= 8) {
count = true;
}
if(pValue.search(e.charCode === [65 - 90]) === 0) {
firstChar = true;
}
console.log(firstChar);
for(var j = 0; j < pLength; j++) {
if(pValue.charAt(j) == "$" || pValue.charAt(j) == "%" || pValue.charAt(j) == "#") {
special = true;
}
}
for(var i = 0; i < pLength; i++) {
if(!isNaN(pValue.charAt(i))) {
hasNum = true;
}
}
if(count && firstChar && hasNum && special) {
document.querySelector("#show_word").textContent = pValue;
}
}
I grabbed the form from some random site because I'm only interested writing the javascript at the moment.
I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.
Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?
I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)
Any thoughts on this would be appreciated.
Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/
document.getElementById("newForm").addEventListener("submit", enterForm);
function enterForm(event) {
event.preventDefault();
var dropdown = document.getElementById('dropDown');
if (document.getElementById('fname').value === ''){
document.getElementById('fname').focus();
alert('Enter text.');
} else if (document.getElementById('eMail').value === ''){
document.getElementById('eMail').focus();
alert('Enter text.');
} else if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
alert('Enter text.');
} else if (!dropDown.value) {
document.getElementById('dropDown').focus();
alert('Choose an option.');
} else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
{ alert ( "Please choose a checkbox" );
return false;
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Please check a radio button.");
return formValid;
return false;
};
If you use HTML5, and assuming you're NOT using jQuery for anything (just native JavaScript), a good convention would be to assign a class to all input elements in the form that you want to validate (or if they all need to be validated, you can get all child elements of the form), and use getElementsByClassName(). With HTML5 data-* attributes, you can assign something like data-invalid-error-message to set the error message for the element itself.
http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
From there, you can perform a loop across all elements, check if they're empty, and then grab the data-invalid-error-message attribute and display it to the user without doing nested if statements.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
document.getElementById("newForm").addEventListener("submit", function (event) {
event.preventDefault();
if (!document.getElementById('fname').value) {
return alert('Enter text.');
}
if (document.getElementById('eMail').value === '') {
document.getElementById('eMail').focus();
return alert('Enter text.');
}
if (document.getElementById('textArea').value === '') {
document.getElementById('textArea').focus();
return alert('Enter text.');
}
var dropdown = document.getElementById('dropDown');
if (!dropdown || !dropDown.value) {
document.getElementById('dropDown').focus();
return alert('Choose an option.');
}
if (( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false )) {
return alert("Please choose a checkbox");
}
var radios = document.getElementsByName("radio");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
}
i++;
}
if (!formValid) {
return alert("Please check a radio button.");
}
// Form is valid here
});
Here is some improvements. Updated Fiddle
I would like to validate form with required property, but it does not support validation of group of options and radio groups
If you're OK not supporting IE8, you can use querySelectorAll to dynamically get all the nodes of different types within your form and validate them accordingly. This will work for a form with any number of inputs:
function validateForm(formNode) {
var formValid = true;
var textFlds = formNode.querySelectorAll('input[type="text"],input[type="email"],input[type="password"],textarea');
var dropdowns = formNode.querySelectorAll('select');
var checks = formNode.querySelectorAll('input[type="checkbox"]');
var anyChecked = false;
var radios = formNode.querySelectorAll('input[type="radio"]');
var anyRadios = false;
for (var i = 0, l = textFlds.length; i < l; i++) {
if (!textFlds[i].value) {
textFlds[i].focus();
alert('Please enter text into the ' + textFlds[i].name + ' field.');
formValid = false
break;
}
};
for (var i = 0, l = dropdowns.length; i < l; i++) {
if (formValid && !dropdowns[i].value) {
dropdowns[i].focus();
alert('Please choose an option from the ' + dropdowns[i].name + ' selector.');
formValid = false
break;
}
};
for (var i = 0, l = checks.length; i < l; i++) {
if (checks[i].checked) {
anyChecked = true;
break;
}
};
if (formValid && !anyChecked) {
alert('Please choose at least one of the checkboxes.');
formValid = false;
}
for (var i = 0, l = radios.length; i < l; i++) {
if (radios[i].checked) {
anyRadios = true;
break;
}
};
if (formValid && !anyRadios) {
alert('Please check a radio button.');
formValid = false;
}
return formValid;
}
document.getElementById('newForm').addEventListener('submit', function (evt) {
evt.preventDefault();
validateForm(this);
});
This could be prettied up a bit, but you get the idea. (fiddle here)
I have a input text which used to filter data in a table using the onkeyup event
<input id="NameFilterText" type="text" onkeyup="return filterDataRow('NameFilterText','Name'); return false;" /></td>
I'm calling this JavaScript function in the onkeyup to the filter data
function filterDataRow(field, name) {
var textBox = document.getElementById(field);
var columnName = name;
var table = document.getElementById('table1');
var headRow = table.rows[0];
var column = 0
var text = textBox.value;
for (var i = 0; i < headRow.cells.length; i++) {
var cellName = headRow.cells[i].innerHTML;
if (cellName == columnName) {
column = i;
break;
}
}
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].style.display = 'table-row'; // execute only when pressing backspace
for (var v = 0; v < text.length; v++) {
var CurCell = table.rows[i].cells[column];
var CurCont = CurCell.innerHTML.replace(/<[^>]+>/g, "");
var reg = new RegExp(text + ".*", "i");
if (CurCont.match(reg) == null) {
table.rows[i].style.display = 'none';
}
}
}
return false;
}
I don't want to execute that commented line if the pressed key is not backspace. How can I do that ?
var input = document.getElementById('NameFilterText');
var keydown=0;
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
keydown=1;
return false;
};
Now in your code filterDataRow()
if(keydown=1){ do your thing. and set keydown = 0 again}
Hope it Helps !
First you need to change the onkeyup event to this:
<input ... onkeyup="filterDataRow('NameFilterText','Name');" />
Then inside the function edit the line you want to be executed only one time adding this if-statement:
if (window.event.keyCode == 8) table.rows[i].style.display = 'table-row';
I wrote a library called keysight that does this kind of thing for all keyboard keys:
node.addEventListener("keydown", function(event) {
var key = keysight(event).key
if(key === '\b') {
console.log("We got one!")
}
})
I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.
Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}
you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.
Trying to allow a user to type into a textarea, but if a certain word is seen, I would like the cursor to stop until that word is removed.
I have finding the word, but I am unable find a way to have the cursor stop.
Any ideas on how i would do this in javascript
$(function() {
$('#ideacomment').bind('keyup', function(e){
var characterLimit = 300;
charactersUsed = $(this).val().length;
if(charactersUsed > characterLimit){
charactersUsed = characterLimit;
$(this).val($(this).val().substr(0, characterLimit));
$(this).scrollTop($(this)[0].scrollHeight);
}
var charactersRemaining = characterLimit - charactersUsed;
$('#remainingCharacters').html(charactersRemaining);
var words = $('#ideacomment').val().split(/\b[\s,\.-:;]*/);
var wordcount = words.length;
var nonewords = new Array("f**k", "you");
var nonewordcount = nonewords.length;
//console.log(nonewordcount + ' is the count');
for(var i = 0; i < wordcount; i++) {
for(var t = 0; t < nonewordcount; t++) {
if(words[i] == nonewords[t]) {
message('No swearing please! <br><br> This post will not succeed!<br><br> Please remove it before you continue!', '430');
}
}
}
});
});
The code above counts the number of chars and also checks each word. Would I would like and I have tried without success is have it as if it ran out of space. But i have been unable to make it happen using the same code the limiter?
This is the new code. Still not working though:
$(function() {
$('#ideacomment').bind('keyup', function(e){
var characterLimit = 300;
charactersUsed = $(this).val().length;
if(charactersUsed > characterLimit){
charactersUsed = characterLimit;
$(this).val($(this).val().substr(0, characterLimit));
$(this).scrollTop($(this)[0].scrollHeight);
}
var charactersRemaining = characterLimit - charactersUsed;
$('#remainingCharacters').html(charactersRemaining);
var nonewords = new Array("hey", "you");
var nonewordcount = nonewords.length;
for(var t = 0; t < nonewordcount; t++) {
if ($(this).val().indexOf(nonewords[t]) != -1) {
message('No swearing please! <br><br> This post will not succeed!<br><br> Please remove it before you continue!', '430');
var keycode = e.charCode || e.keyCode;
console.log(keycode);
if (keycode !== 8 && keycode !== 46)
return false;
}
}
});
});
You could check which key is being pressed, and block it if it is not a Backspace or Delete. Here is a simplified example:
$(function() {
$('#textbox').keydown(function(e) {
if ($(this).val().indexOf('test') != -1) {
var keycode = e.charCode || e.keyCode;
if (keycode !== 8 && keycode !== 46)
return false;
}
});
});
jsFiddle Demo
Since you already seem to have the text-checking and notification part, all you're really missing is just the keypress-blocking part.