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>
Related
I am building a form sending function in JavaScript, and I have run into a problem where it executes an else if statement every time. Here is my script:
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
The problem being that the else if(el != "#submit"){} runs even when the id in question is "#submit". Does anyone know why this doesn't work?
To help, here is my php document, and the rest of the form constructer:
php:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<?php if(!$_GET): ?>
<form id="form1">
<input type="text" id="input1" name="name"/>
<br>
<select id="dropdown" name="color">
<option id="null" name="null"></option>
<option id="opt1" name="blue">blue</option>
<option id="opt2" name="yellow">yellow</option>
</select>
<br>
<button type="submit" id="submit" name="submit"onclick="form1.submit()">Submit data</button>
</form>
<script src="http://charlie/form.js"></script>
<script>
var form1 = new form("form1");
form1.setElements();
form1.logElements();
</script>
<?php elseif(!(isset($_GET['name']) || isset($_GET['color']))): ?>
<p style="color:red">ERROR! form.js failed</p>
<?php else: ?>
<p><?= $_GET['name'] ?></p>
<p><?= $_GET['color'] ?></p>
<?php endif; ?>
</body>
</html>
form constructer:
function form(id) {
this.id = "#" + id;
this.url = window.location.href;
this.elements = [];
this.names = [];
this.setElements = function() {
var elements = [],names = [],children = $(this.id).children();
for(var i = 0; i < children.length; i++) {
var childid = children[i].id;
if(childid)
{
elements.push('#' + childid);
}
}
this.elements = elements;
for(var e in this.elements) {
names.push($(this.elements[e]).attr('name'));
}
this.names = names;
};
this.logElements = function() {
for(var e in this.elements) {
console.log(this.elements[e]);
}
for(var n in this.names) {
console.log(this.names[n]);
}
};
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
}
Turning my comment into an answer with some code. The "in" operator in Javascript iterates over properties not the elements at each index. To make your current code work, change the code to the following:
var el;
var elementCount = this.elements.length;
for (var i = 0; i < elementCount; i++) {
el = this.elements[i];
This will produce the expected behavior.
The for...in loop is the cause. el tkaes the values 0, 1, 2 ...you need to compare this.elements[el] instead of el :
if(this.elements[el] == "#dropdown") ...
else if(this.elements[el] != "#submit") {
...
Please see the fiddle link at the bottom. I have two questions:
How to add HTML text to these radio buttons. I have to give them $ and % value (for the user).
Find the values of every radio button selected. For example, the user added 10 rows (each having 2 radio buttons). I have iterated a loop to find the input type and see if the button is checked and then find its value.
NOT WORKING, guide me what wrong am I doing.
FIDDLE
var i=0;
window.myAdd = function(){
var x = i;
var butts = document.createElement("INPUT");
butts.setAttribute("type", "radio");
butts.setAttribute("name", "currency"+x);
butts.setAttribute("value", "%");
butts.setAttribute("id", "radio"+i);
//var node = document.createTextNode("%");
//butts.appendChild(node);
i=i+1;
//console.log(butts);
var butts_1 = document.createElement("INPUT");
butts_1.setAttribute("type", "radio");
butts_1.setAttribute("name", "currency"+x);
butts_1.setAttribute("value", "$");
butts_1.setAttribute("id", "radio"+i);
i=i+1;
//console.log(butts_1);
var row = document.createElement("TR");
//document.getElementById('tab').appendChild(butts);
//document.getElementById('tab').appendChild(butts_1);
row.appendChild(butts);
row.appendChild(butts_1);
document.getElementById('tab').appendChild(row);
x=x+1;
}
window.myfunction = function(table){
//var x = String(document.getElementById('radioP').value);
//alert(x);
for(var i=0;i<table.elements.length;i++){
if(table.elements[i].type =='radio'){
if(table.elements[i].checked == true){
alert(table.elements[i].value);
}
}
}
}
I have corrected your script to work:
var i = 0;
window.myAdd = function() {
var x = i;
var butts = document.createElement("INPUT");
butts.setAttribute("type", "radio");
butts.setAttribute("name", "currency" + x);
butts.setAttribute("value", "%");
butts.setAttribute("id", "radio" + i);
//var node = document.createTextNode("%");
//butts.appendChild(node);
i = i + 1;
//console.log(butts);
var butts_1 = document.createElement("INPUT");
butts_1.setAttribute("type", "radio");
butts_1.setAttribute("name", "currency" + x);
butts_1.setAttribute("value", "$");
butts_1.setAttribute("id", "radio" + i);
i = i + 1;
//console.log(butts_1);
var row = document.createElement("TR");
//document.getElementById('tab').appendChild(butts);
//document.getElementById('tab').appendChild(butts_1);
row.appendChild(butts);
row.appendChild(butts_1);
document.getElementById('mytable').appendChild(row);
x = x + 1;
}
window.myfunction = function(table) {
//var x = String(document.getElementById('radioP').value);
//alert(x);
//debugger;
for (var i = 0; i < table.rows.length; i++) {
var row = table.rows[i];
for (var j = 0; j < row.childNodes.length; j++) {
if (row.childNodes[j].type == 'radio') {
if (row.childNodes[j].checked == true) {
alert(row.childNodes[j].value);
}
}
}
}
}
<button onclick='myAdd()'>Add Radio Buttons</button>
<table id="mytable" name="mytable"></table>
<button onclick='myfunction(document.getElementById("mytable"))'>GET VALUE</button>
1) You have to use <label> element, e.g.:
<input id="radio_1" type="radio" value="1" />
<label for="radio_1">$</label>
<input id="radio_2" type="radio" value="2" />
<label for="radio_2">%</label>
2) You have to iterate through them. Considering all of the radios are within some div with class "container", you'll need something like this:
document.getElementById('get_values').addEventListener('click', function() {
var radios = document.querySelectorAll('.container input[type="radio"]');
values = {};
for(i=0; i<radios.length; i++) {
var radio = radios[i];
var name = radio.getAttribute('name');
if(radio.checked) {
values[name] = radio.value;
} else {
values[name] = values[name] || null;
}
}
alert(JSON.stringify(values));
});
See this fiddle: http://jsfiddle.net/andunai/gx6quyo0/
I'm new to Javascript.
I want to store input boxes value in array, but I have problem with this.
I use below code; please guide me:
<form>
<input type="text" id="NumElement" />
<button onclick="return Give()" />Give</button>
<div id="inputs"></div>
<p>Block Number: <input type="text" id="NoArrey" /></p>
<button onclick="return Show()" />Show</button>
<input type="text" id="Result" />
</form>
<script>
function Give() {
var Num = document.getElementById('NumElement').value;
var i = 0;
for (i = 0; i < Num; i++) {
var m = i + 1;
inputs.innerHTML = inputs.innerHTML +"<br><input type='text' id='v" + m + "'>";
};
inputs.innerHTML = inputs.innerHTML +"<br><button id='Save' onclick='return Save()'>Save</button>";
return false;
}
function Save() {
var MyArray = new Array();
var j = 0;
for (j = 0; j < Num; j++) {
var InputValue = document.getElementById('v' + j);
MyArray.push(InputValue.value);
}
function Show() {
var no = document.getElementById('NoArrey').value;
document.getElementById("Result").value = (MyArray[no]);
return false;
}
</script>
Maybe you did a typo but in the save() function you don't declare var num. You are declaring num in the give() function.
this should work.
EDIT:
function Give() {
var Num = document.getElementById('NumElement').value;
var i = 0;
for (i = 0; i < Num; i++) {
var m = i + 1;
inputs.innerHTML = inputs.innerHTML +"<br><input type='text' id='v" + m + "'>";
};
inputs.innerHTML = inputs.innerHTML +"<br><button id='Save' onclick='return Save()'>Save</button>";
return false;
}
function Save() {
var Num = document.getElementById('NumElement').value;
var MyArray = new Array();
var j = 0;
for (j = 0; j < Num; j++) {
var InputValue = document.getElementById('v' + j);
MyArray.push(InputValue.value);
}
function Show() {
var no = document.getElementById('NoArrey').value;
document.getElementById("Result").value = (MyArray[no]);
return false;
}
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";
}
}
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++) {