Javascript for showing Div on click using getElementsByClassName - javascript

I have a <div> in my page like this:
<div class="errordiv" style="display: none;">Username is empty</div>
I have an input field and a button like this:
<input type="textbox" id="txt1" />
<input type="button" value="Submit" id="btn1" onclick="validate();" />
I have tried this,
function validate() {
//alert('hi');
var inptextbox = document.getElementById('txt1');
//alert('level zero');
var errorMsg = document.getElementsByClassName('errordiv').item();
//alert('level ground');
if (inptextbox.value == '') {
//alert('hi2');
errorMsg.style.display = 'block';
} else {
errorMsg.style.display = 'none';
}
}
The above js code is not working. I am not getting the level ground alert. I don't know what is missing.
P.S : I don't want Jquery as my page has some restriction to use library files.

You need to return false in validate to stop the form from submitting, which reloads the page
EDIT
added polyfill for getElementsByClassName with support for IE7 from https://gist.github.com/2299607
// Add a getElementsByClassName function if the browser doesn't have one
// Limitation: only works with one class name
// Copyright: Eike Send http://eike.se/nd
// License: MIT License
if (!document.getElementsByClassName) {
 document.getElementsByClassName = function(search) {
var d = document, elements, pattern, i, results = [];
if (d.querySelectorAll) { // IE8
 return d.querySelectorAll("." + search);
}
if (d.evaluate) { // IE6, IE7
 pattern = ".//*[contains(concat(' ', #class, ' '), ' " + search + " ')]";
 elements = d.evaluate(pattern, d, null, 0, null);
 while ((i = elements.iterateNext())) {
results.push(i);
 }
} else {
 elements = d.getElementsByTagName("*");
 pattern = new RegExp("(^|\\s)" + search + "(\\s|$)");
 for (i = 0; i < elements.length; i++) {
if ( pattern.test(elements[i].className) ) {
 results.push(elements[i]);
}
 }
}
return results;
 }
}
function validate() {
//alert('hi');
var inptextbox = document.getElementById('txt1');
//alert('level zero');
var errorMsg = document.getElementsByClassName('errordiv')[0];
//alert('level ground');
if (inptextbox.value == '') {
//alert('hi2');
errorMsg.style.display = 'block';
return false;
} else {
errorMsg.style.display = 'none';
}
}

Your code works in chrome. This is the demo.
document.getElementsByClassName will not work for some old browsers, check here.

First off you'll need to return a value from your function to stop the page posting back if a validation even occurs, change your HTML to:
<input type="button" value="Submit" id="btn1" onclick="return validate();" />
Then your script to:
function validate() {
var inptextbox = document.getElementById('txt1');
var errorMsg = document.getElementsByClassName('errordiv').item();
if (inptextbox.value == '') {
errorMsg.style.display = 'block';
return false;
}
return true;
}

Related

How to access values of Input in a List

For my Project I need to have a site, which can generate a custom amount of Inputs, which will become buttons in another page.
And I need the values for the Input in order to Label the Buttons correctly.
HTML
<h2>settings:</h2>
<p>Add Amount of Checks:</p>
<input id="NumOfButtons"
name="NumOfButtons"
pattern=""
size="30"
spellcheck="false"
title="Amount of Checks"
value="">
<script>
let input = document.getElementById("NumOfButtons");
let listTA = new Array;
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
var x = parseInt(document.getElementById("NumOfButtons").value);
listTA = new Array(x);
for (let i = 0; i < x; ++i) {
var textarea = document.createElement("input");
textarea.name = "input";
textarea.maxLength = "100";
textarea.id = "TextAreaID"
listTA[i] = textarea;
document.getElementById("Buttons").appendChild(textarea);
}
}
});
</script>
<div id="Buttons">
<br />
<button onclick="sendDataAndGoToKontrolle()">save & continue</button>
<p>Reset F5</p>
</div>
<script>
function sendDataAndGoToKontrolle() {
var filtered;
if (listTA != null) {
let x = new Array;
for (let i = 0; i < listTA.length; ++i) x[i] = listTA[i].document.getElementById("TextAreaID").value;
if (!(x.length === 0)) {
for (let i = 0; i < x.length; ++i) {
if (x[i] === null) {
var filtered = x.filter(function (el) { return el != null; });
console.log("TextAreas filtered!")
} else console.log("Nothing to filter!")
}
} else console.log("Nothin written in TextAreas!");
} else console.log("No TextArea created!");
if (!(filtered === null)) {
//Send Prüfungen to Controller
$.ajax({
url: "#Url.Action("NewIDSettingsPage")",
type: "GET",
data: { Prüfungen: filtered },
success: function () {
console.log("Successfully sent!");
//window.location.href = '/home/NewIDSettingsPage';
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log("ERROR: " + errorMessage);}});
} else console.log("ERROR");
}
</script>
The result should be a list/Array of string(values of the Inputs).
If you need any further information, please write a Comment and I will look to reply quickly.
Do not give all the input elements the same id. textarea.id = "TextAreaID" is wrong.
If you want to group the inputs together you should set the class:
textarea.className = "TextAreaClass"
Or if you want to give each one an id, append i to the id to make it unique:
textarea.id = "TextAreaID"+i;
When trying to get the values of your inputs you have the following:
x[i] = listTA[i].document.getElementById("TextAreaID").value;
Which doesn't make a lot of sense. What you should probably be doing is:
x[i] = listTA[i].value;
Because you have stored the element in the array, you don't need to get the element from the document.

JavaScript add error message to character counter for html form?

I have created a character counter for a textarea field on a form in an HTML page. I have a separate .js file to validate fields like name, Email, etc. I need to COMBINE my new code that validates if a user typed over 140 characters into my current validate.js file. Below is part of my HTML form, new code, validation, counter, and helper function. If I add my new code to my validation.js, it does not work. How do I combine the two? Thank you for those that help.
HTML FORM
<label for="comments">Comments:</label><span id="comment-count" class="hide"></span>
<br>
<textarea name="comments" id="comments" rows="4" cols="40"></textarea><br>
<span id="comments.error"></span><br>
<input type="submit" value="Submit" name="submit"/>
</fieldset>
<script src="utilities.js"></script>
<script src="counter.js"></script>
<script src="validate.js"></script>
</form>
NEW CODE
var comment = document.forms["contactform"]["comments"].value;
var count = document.getElementById('comment-count');
var countError = document.getElementById('count');
var valid = count.value.length <= 130;
if (!valid)
{
countError.innerHTML = "test";
ret = false;
}
else
{
countError.innerHTML = "";
}
validate.js
function validateForm()
{
var ret = true;
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('name.error');
if (name == "")
{
nameError.innerHTML = "Please enter your name";
ret = false;
}
else
{
nameError.innerHTML = "";
}
var email = document.forms["contactform"]["email"].value;
var emailError = document.getElementById('email.error');
var valid = /[^#]+#[^#]+/.test(email);
if (!valid)
{
emailError.innerHTML = "Please enter a valid Email";
ret = false;
}
else
{
emailError.innerHTML = "";
}
var type = document.forms["contactform"]["service"].value;
var serviceError = document.getElementById('service.error');
if (document.getElementById('service').selectedIndex == "")
{
serviceError.innerHTML = "You must select a service";
ret = false;
}
else
{
serviceError.innerHTML = "";
}
var comments = document.forms["contactform"]["comments"].value;
var commentsError = document.getElementById('comments.error');
if (comments == "")
{
commentsError.innerHTML = "Please provide a description";
ret = false;
}
else
{
commentsError.innerHTML = "";
}
return ret;
}
CHARACTER COUNTER
(function ()
{
var comment = document.getElementById('comments');
var commentCount = document.getElementById('comment-count');
addEvent(comment, 'focus', updateCounter);
addEvent(comment, 'input', updateCounter);
addEvent(comment, 'blur', function ()
{
if (comment.value.length <=140)
{
commentCount.className = 'hide';
}
});
function updateCounter(e)
{
var target = e.target || e.srcElement;
var count = 140 - target.value.length;
if (count < 0)
{
commentCount.className = 'error';
}
else if (count <=15)
{
commentCount.className = 'warn';
}
else
{
commentCount.className = 'good';
}
var charMsg = '<b>' + count + '</b>' + ' characters';
commentCount.innerHTML = charMsg;
}
}());
HELPER FUNCTION
function addEvent(el, event, callback)
{
if ('addEventListener' in el)
{
el.addEventListener(event, callback, false);
}
else
{
el['e' + event + callback] = callback;
el[event + callback] = function()
{
el[event + callback](window.event);
};
el.attachEvent('on' + event, el[event + callback]);
}
}

How do i turn this jquery into javascript

Hi I can't use Jquery here. please help me change these 3 selector into javascript.
I already tried document.getElementById('FeedbackLightBox_txtName').value; but i doesn't work.
<script type="text/javascript">
function SetButtonStatus() {
var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5)
makeBtn();
else
$('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(false);
}
function makeBtn() {
$('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(true);
}
function ClearValues(sender, args) {
$('#FeedbackLightBox_txtName').val('');
$('#FeedbackLightBox_txtMessage').val('');
$('#FeedbackLightBox_txtEmail').val('');
args.set_cancel(true);
return false;
}
</script>
Like this?
document.getElementById('FeedbackLightBox_btnSubmit').control.set_enabled(false);
document.getElementById('FeedbackLightBox_txtName').value = '';
JFYI
When you say
$('#FeedbackLightBox_btnSubmit')[0] // it gives you an access to HTML element object which is equivalent to saying `document.getElementById('Feed..)`.
not sure, where .control.set_enabled(false); is defined on the element, but I guess you do know.
function SetButtonStatus() {
var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5) {
makeBtn();
} else {
document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(false);
}
}
function makeBtn() {
document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(true);
}
function ClearValues(sender, args) {
document.getElementById("FeedbackLightBox_txtName").value = '';
document.getElementById("FeedbackLightBox_txtMessage").value = '';
document.getElementById("FeedbackLightBox_txtEmail").value = '';
args.set_cancel(true);
return false;
}
It seems you have a form something like:
<form id="FeedbackLightBox_form" onsubmit="return validate(this)" action="">
Name: <input name="FeedbackLightBox_txtName"><br>
Message: <teaxtArea name="FeedbackLightBox_txtMessage"></textarea><br>
Email: <input name="FeedbackLightBox_txtEmail"><br>
<input type="submit" id="FeedbackLightBox_btnSubmit"> <input type="reset">
</form>
that you want to check something has been entered into each field before submission, so you validate it using:
function validate(form) {
var control, controls = form.controls;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.type != 'submit' && control.value.length < 5) {
return false;
}
}
}
The clearForm function is entlirely unnecessariy if you inlcude a reset button, but anyway:
function clearForm() {
document.getElementById('FeedbackLightBox_form').reset();
}
Similarly, the (inappropriately named) makeBtn function can be:
function makeBtn() {
document.betElementById('FeedbackLightBox_btnSubmit').disabled = false;
}
Maybe it should be called enableBtn?
Looks like jQuery is only used for getting HTML elements so you could define these as global variables before your functions (or pass them as function arguments) to avoid duplication.
var tb1 = document.getElementById('FeedbackLightBox_txtName');
var tb2 = document.getElementById('FeedbackLightBox_txtMessage');
var tb3 = document.getElementById('FeedbackLightBox_txtEmail');
var btn = document.getElementById('FeedbackLightBox_btnSubmit');
function SetButtonStatus() {
if (tb1.value.length >= 5 && tb2.value.length >= 5 && tb3.value.length >= 5)
makeBtn();
else
btn.control.set_enabled(false);
}
function makeBtn() {
btn.control.set_enabled(true);
}
function ClearValues(sender, args) {
tb1.value = '';
tb2.value = '';
tb3.value = '';
args.set_cancel(true);
return false;
}

Why is this javascript object referring to a previous object's properties?

I am creating a class that can create any number of captchas on a page.I have a captcha class that I am using to instantiate new captcha objects c1 and c2. Here is my JS:
$(function(){
var captcha = {
parentForm : '',
container : '',
captcha_input : '',
number1 : 0,
number2 : 0,
createCaptcha : function(form_ID){
var newHtml;
this.parentForm = $('#' + form_ID);
this.container = this.parentForm.find('.captchaContainer');
this.number1 = this.randomNumber(10);
this.number2 = this.randomNumber(10);
newHtml = 'What does ' + this.number1 + ' plus ' + this.number2 + ' equal? <b class="required goldenrod" title="Required Field">*</b><br/><br/><input type="text" name="captcha">';
this.container.html(newHtml);
},
isValid : function(){
console.log(this.container);
this.captcha_input = this.container.find('input[name="captcha"]');
if (this.number1 + this.number2 == this.captcha_input.val()) {
this.captcha_input.css('background-color', '')
return true;
} else{
this.captcha_input.css('background-color', '#FFCCCC')
alert(this.number1 + ' plus ' + this.number2 + ' does not equal ' + this.captcha_input.val() + '. Please try again.');
this.captcha_input.focus();
return false;
}
},
randomNumber : function(max){ return Math.floor(Math.random()*(max+1)); }
}
var c1 = captcha,
c2 = captcha;
c1.createCaptcha("form1");
c2.createCaptcha("form2");
$('#form1 input[type="submit"]').click(function() {
if(c1.isValid()){
alert('Captcha is valid!');
}else{
return false;
}
});
$('#form2 input[type="submit"]').click(function() {
if(c2.isValid()){
alert('Captcha is valid!');
}else{
return false;
}
});
});
And my HTML:
<form id="form1">
<div class="captchaContainer"></div>
<input type="submit">
</form>
<form id="form2">
<div class="captchaContainer"></div>
<input type="submit">
</form>
When I click on form1's submit button, it seems like the isValid method is being ran for c2 and not c1 like I expect. Any idea why this is doing so?
A few things to note:
If I add more captcha instances and HTML, each submit button will run isValid on the last instance of captcha on click.
This needs to work for IE8+
Here is a fiddle of the code in action.
Any help would be greatly appreciated. Thanks!
c1 and c2 are both the same object. Use Object.create to create different instances. Object.create is not supported in old browsers, however there's a polyfill in the link I provided.
var c1 = Object.create(captcha),
c2 = Object.create(captcha);
You can also perform a deep copy of the object.
function deepCopy(obj) {
var res = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
res[key] = obj[key];
};
}
res.prototype = obj.prototype; // this would make it a deep copy.
return res;
};
var c1 = deepCopy(captcha);
While #plalx had a valid answer, it wasn't an ideal answer for my scenario. Since I cannot instantiate a class that was created from an object literal (without use of Object.create), I decided to refactor my class with a function instead:
$(function(){
var Captcha = function(){
var parentForm = '',
container = '',
captcha_input = '',
number1 = 0,
number2 = 0,
createCaptcha = function(form_ID){
var newHtml;
this.parentForm = $('#' + form_ID);
this.container = this.parentForm.find('.captchaContainer');
this.number1 = randomNumber(10);
this.number2 = randomNumber(10);
newHtml = 'What does ' + this.number1 + ' plus ' + this.number2 + ' equal? <b class="required goldenrod" title="Required Field">*</b><br/><br/><input type="text" name="captcha">';
this.container.html(newHtml);
},
isValid = function(){
this.captcha_input = this.container.find('input[name="captcha"]');
if (this.number1 + this.number2 == this.captcha_input.val()) {
this.captcha_input.css('background-color', '')
return true;
} else{
this.captcha_input.css('background-color', '#FFCCCC')
alert(this.number1 + ' plus ' + this.number2 + ' does not equal ' + this.captcha_input.val() + '. Please try again.');
this.captcha_input.focus();
return false;
}
},
randomNumber = function(max){ return Math.floor(Math.random()*(max+1)); }
return{
createCaptcha : createCaptcha,
isValid : isValid
}
}
// Instantiation of Captcha objects
var c1 = new Captcha,
c2 = new Captcha;
c1.createCaptcha("form1");
c2.createCaptcha("form2");
$('#form1 input[type="submit"]').click(function() { if(c1.isValid()){ alert('Captcha is valid!'); }else{ return false; } });
$('#form2 input[type="submit"]').click(function() { if(c2.isValid()){ alert('Captcha is valid!'); }else{ return false; } });
});
Here is the new working fiddle
TLDR: Since object literals cannot be instantiated without Object.create, I used a function to create the class instead, and then instantiated like so:
var c1 = new Captcha,
c2 = new Captcha;

Disable ajax form button on key press

I have a button on an Ajax form that when pressed, indicates to the user that it is "searching" kind of a small "throbber" to keep the user occupied while the DB is being queried.
When the submit button is clicked it goes to a function. That function will disable the button, gather up what is filled out on the form, perform the Ajax call (non-asynchronous - meaning the script is to WAIT on the call to complete before moving on to the next line of code) and then re-enable the button.
Like so:
function CheckForm()
{
disableButton(document.getElementById("save"));
....... lots of instructions in here ........
....... Loops through every form el .........
//Ajax called
CallAjax(sUrls, sParams);
enableButton(document.getElementById("save"));
}
function disableButton(element)
{
try
{
disabledEl = element.id
disabledElOrigTxt = element.value;
element.value = ' Loading...'
addClass(element, "pleaseWait");
addClass(document.myForm.reset, "resetWait");
element.disabled = true;
document.myForm.reset.disabled = true;
//return true;
}
catch(e)
{
////SHHHHHH
}
}
function enableButton(element, timer)
{
try
{
if(element.value == ' Loading...')
element.value = disabledElOrigTxt;
removeClass(element, "pleaseWait");
removeClass(document.myForm.reset, "resetWait");
element.disabled = false;
document.myForm.reset.disabled = false;
clearTimeout(timer);
return true;
}
catch(e)
{
////SHHHHHH
}
}
function hasClass(element, className)
{
var classes = element.className.split(' ');
var len = classes.length;
for (var i=0; i<len; i++)
{
if (classes[i] == className)
return true;
}
return false;
}
function addClass(element, className)
{
if (!hasClass(element, className))
element.className = (element.className == '' ? className : element.className + ' ' + className);
}
function removeClass(element, className)
{
var newValue = '';
var classes = element.className.split(' ');
var len = classes.length;
for (var i=0; i<len; i++)
{
if (classes[i] != className)
newValue += newValue.length ? ' ' + classes[i] : classes[i];
}
element.className = newValue;
}
This works in Mozilla, IE, but NOT CHROME. Anyone have any idea why?
If I modify disableButton() and make it alert("hi") on the last line of the try, in Chrome I can observe the button change.... but ONLY if I throw an alert in there to stop the script. Obviously that is not what I want to do.
Maybe your CallAjax() function works asynchronously in Chrome?
Another possibility, maybe Chrome processes it so fast you don't notice the changes?

Categories

Resources