Javascript for showing a div using the div's class name - javascript

I have a div in my page like that,
<div class="errormsg" style="display: none;">Username is empty</div>
i am having an input field like this,
<input type=textbox id="userid" />
Now i need a javascript for showing the error message div if input field was empty. I need to use the div class rather than id. Please help.
P.S : I don't want Jquery as my page has some restriction to use library files.

Try this, assuming only one errormsg div -
Update
I've added a fiddle here. Plus, there was a typo - corrected
<div class="errormsg" style="display: none;">Username is empty</div>
<input type=textbox id="userid" onchange="validate()" />
function validate(){
var userId = document.getElementById('userId'),
errorMsg = document.getElementsByClassName('errormsg').item();
if (userId.value === ''){
errorMsg.style.display = 'block'
} else {
errorMsg.style.display = 'none';
}
}

<div class="errormsg">Username is empty</div>
<input type='textbox' id="userid" onkeyup="javascript:call(this);" />
function getElementsByClassName(className) {
// For IE
if (document.all) {
var allElements = document.all;
} else {
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++) {
if (allElements[i].className == className) {
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
function call(control)
{
var userid=document.getElementById('userid');
var errorMsg = getElementsByClassName('errormsg')[0];
if(userid.value == '')
{
errorMsg.style.display = "block";
}
else
{
errorMsg.style.display = "none";
}
}

Removed the JQuery and added the Javascript code as below:
<div class="errormsg">Username is empty</div>
<input type='textbox' id="userid" onkeyup="javascript:call(this);" />
function getElementsByClassName(className) {
// For IE
if (document.all) {
var allElements = document.all;
} else {
var allElements = document.getElementsByTagName("*");
}
var foundElements = [];
for (var i = 0, ii = allElements.length; i < ii; i++) {
if (allElements[i].className == className) {
foundElements[foundElements.length] = allElements[i];
}
}
return foundElements;
}
function call(control)
{
var userid=document.getElementById('userid');
var errorMsg = getElementsByClassName('errormsg')[0];
if(userid.value == '')
{
errorMsg.style.display = "block";
}
else
{
errorMsg.style.display = "none";
}
}

Related

I need to take the information from them and write to the variable "Vidpovid". How can this be done?

I have a problem. I am creating "input" fields dynamically. I need to take the information from them and write to the variable "Vidpovid". How can this be done?
Code HTML
<div class="form-group" id="input">
<button type="button" onclick="createNewInput()">new input</button>
<input type="number" id="1" class="form-control" /><br />
<ol id="base-list"></ol>
<br />
<input type="hidden" asp-for="Less_Check.Vidpovid" class="form-control" />
</div>
Code JS
let id = 2;
function createNewInput() {
let addNewInput = true;
for(let i = 1; i < id; i++)
{
if(document.getElementById(i).value == "")
{addNewInput = false;}
}
if(addNewInput)
{
let baseList = document.getElementById('base-list')
let newInput = document.createElement("input");
newInput.setAttribute("type", "number");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", id);
id++;
baseList.append(newInput);
baseList.append(document.createElement("br"));
}
else
{
alert("error");
}
}
A simple demo you could follow:
<script>
let id = 2;
function createNewInput() {
let addNewInput = true;
for (let i = 1; i < id; i++) {
if (document.getElementById(i).value == "") { addNewInput = false; }
}
if (addNewInput) {
let baseList = document.getElementById('base-list')
let newInput = document.createElement("input");
newInput.setAttribute("type", "number");
newInput.setAttribute("class", "form-control");
newInput.setAttribute("id", id);
id++;
baseList.append(newInput);
baseList.append(document.createElement("br"));
}
else {
alert("error");
}
//add the following code to set the value for hidden input..
const arr = Array.from(
document.querySelectorAll('input[type=number]'),
input => input.value
).filter(n=>n);
document.getElementById("Less_Check_Vidpovid").value = arr.join(",");
}
</script>
Result:

Why the script is not running on all input elements?

I am using this script to hide the default value of input elements on my page:
<script>
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text
window.onload = formDefaultValues;
function formDefaultValues() {
var fields = getElementsByClassName(document, "input", "default-value");
if (!fields) {
return;
}
var default_values = new Array();
for (var i = 0; i < fields.length; i++) {
fields[i].style.color = inactive_color;
if (!default_values[fields[i].id]) {
default_values[fields[i].id] = fields[i].value;
}
fields[i].onfocus = function() {
if (this.value == default_values[this.id]) {
this.value = '';
this.style.color = active_color;
}
this.onblur = function() {
if (this.value == '') {
this.style.color = inactive_color;
this.value = default_values[this.id];
}
}
}
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
I use this code to loop on input elements that have the class "default-value" and fire the action on them. It's really working on some elements but not others? What might be going wrong?
Thanks in advance
This worked for me..
<html>
<script>
function ViewAllElements() {
var fe = document.forms['myForm'].elements;
alert(fe.length);
for(var i = 0; i < fe.length; i++)
{
alert(fe[i].value);
}
var ebc = getElementsByClassName(document, "input", "fieldA");
alert(ebc.length);
for(var j = 0; j < ebc.length; j++)
{
alert(ebc[j].value);
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
<body>
<form id="myForm" name="myForm">
<input class="fieldA" id="field1" name="field1" value="field1value">
<input class="fieldA" id="field2" name="field2" value="field2value">
<input class="fieldA" id="field3" name="field3" value="field3value">
<input class="fieldB" id="field4" name="field4" value="field4value">
<input class="fieldB" id="field5" name="field5" value="field5value">
<input class="fieldB" id="field6" name="field6" value="field6value">
<input type="button" onClick="ViewAllElements();" value="View">
</form>
</body>
</html>

Validating Mandatory Input Boxes Using Javascript only

I wanted to know what would be the best method to validate (to ensure that all 4 of the input boxes are not blank)?
<html>
<head></head>
<body>
<input type="text" id="i1">
<input type="text" id="i2">
<input type="text" id="i3">
<input type="text" id="i4">
</body>
</html>
If they are all to be inputs then you can use document.getElementsByTagName
var allinputs = document.getElementsByTagName("input");
console.log(allinputs);
for (var i = 0; i < allinputs.length; i++) {
if(allinputs[i].value.length == 0){
alert('need to have something here');
return;
}
}
here is a working fiddle
JQuery Validate is an really easy way to validate your fields. You can read more about it at their wiki:
http://docs.jquery.com/Plugins/Validation
My custom method, not cross-browser:
NodeList.prototype.every = HTMLCollection.prototype.every = Array.prototype.every;
var allChecked = document.querySelectorAll('input[type=text]').every(function(el) {
return el.value !== '';
});
if (allChecked) alert("All checked!");
The cross-browser (IE8 and above), not funny way:
var inputs = document.querySelectorAll('input[type=text]');
var allChecked = true;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].value === '') {
allChecked = false;
}
}
if (allChecked) alert("All checked!");
HTML:
<input type="button" value="submit" onclick="submitForm()">
JavaScript :
function submitForm()
{
if(validate())
{
alert('No blank found!!');
}
else
{ alert('blank found!!'); }
}
function validate()
{
var i1 =document.getElementById('i1').value;
var i2 =document.getElementById('i2').value;
var i3 =document.getElementById('i3').value;
var i4 =document.getElementById('i4').value;
var result = false;
if( i1 && i2 && i3 && i4) {
result = true;
}
return result;
}

checking for duplicate file while uploading multiple file in Javascript

I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {

changing content of p element using innerHTML

I have the following script:
var before = document.getElementById('before');
if (switchElement.value == 'single'){
for (var i=0; i < before.length; i++) {
if (before[i].id == "before_label") {
before[i].innerHTML = 'Image';
break;
}
}
after.style.display = 'none';
}
and the HTML looks like:
<div id="before">
<p id="before_label"> Before Image: </p>
<input type="file" name="before" size="40">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
</div>
Was wondering why it didn't work and change the inner html to change?
To access the innerHTML of before_label, just access it directly:
document.getElementById('before_label').innerHTML = 'Image';
getElementById only returns one element. You need to acces the child objects via childNodes.
Try this:
var before = document.getElementById('before').childNodes;
if (switchElement.value == 'single'){
for (var i=0; i < before.length; i++) {
if (before[i].id == "before_label") {
before[i].innerHTML = 'Image';
break;
}
}
after.style.display = 'none';
}
Why the for loop? Just get the element by its id:
var before_label = document.getElementById('before_label');
if (switchElement.value == 'single') {
before_label.innerHTML = 'Image';
after.style.display = 'none';
}

Categories