I need to get the id of an element within a form so I can tag the element as "false" or "true". Or, alternately, I need a way to associate a name with an element that can I pull in javascipt so I can change the associated value.
var form = document.getElementById("myForm");
form.elements[i].value
Those lines of code is what I tried but it doesn't seem to work.
Edit:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm").elements;
for(var i = 0; i < 1 ; i++){
var id = form.elements[i].id;
sessionStorage.setItem(id,"false");
}
localStorage.setItem("run", true);
}
}
So basically when I run the page, I want a localStorage item attached to all the buttons on the screen. I want this to run once so I can set all the items to false. Problem is I don't know how to get the ids so I have a value to attach to the button. Any idea of how to accomplish a task like this.
Edit2:
function initial(){
if (localStorage.getItem("run") === null) {
var form = document.getElementById("myForm");
var tot = document.getElementById("myForm").length;
for(var i = 0; i < tot ; i++){
sessionStorage.setItem(form.elements[i].id,"false");
}
localStorage.setItem("run", true);
}
}
This is the new code. It mostly seems to work but for some reason only the first value is getting set to false. Or maybe it has to do with this function, I'm not sure.
function loader(){
var form = document.getElementById("myForm");
var tot = 5;
for(var i = 0; i < 5 ; i++){
if(sessionStorage.getItem(form.elements[i].id) === "true"){
document.getElementById(form.elements[i].id).style.backgroundColor = "green";
return ;
}else{
document.getElementById(form.elements[i].id).style.backgroundColor = "red";
return false;
}
}
}
Anyways, I'm running both of these at the same time when the page is executed so they are all set to false and turn red. But when a button is properly completed, the color of the button turns green.
It's available via the id property on the element:
var id = form.elements[i].id;
More on MDN and in the spec.
Live Example:
var form = document.getElementById("myForm");
console.log("The id is: " + form.elements[0].id);
<form id="myForm">
<input type="text" id="theText">
</form>
You're already storing all the elements in the form so it must be :
var form = document.getElementById("myForm").elements;
var id = form[i].id;
Or remove the elements part from the form variable like :
var form = document.getElementById("myForm");
var id = form.elements[i].id;
I am new to angularjs and getting some problem on checkbox values on edit profile page.
I have an array for checkbox
$scope.checkBoxes = [
{id:'1', value:'Reading'},
{id:'2', value:'Cooking'},
{id:'3', value:'Dancing'},
{id:'4', value:'Singing'}
];
and I have used ng-repeat for showing checkbox
<div ng-repeat="checkBox in checkBoxes" style="display:inline;">
<input type="checkbox" ng-model="checkBox.selected" id={{checkBox.id}}' ng-checked="checkItem(checkBox.id)" ng-change="listActionsHandler(checkBoxes)">{{ checkBox.value }}
</div>
This is my ng-change function:
$scope.listActionsHandler = function(list) {
var has = [];
angular.forEach(list, function(item) {
if ( angular.isDefined(item.selected) && item.selected === true ) {
has.push(item.id);
}
});
formData['hobby'] = has;
}
and this is my ng-checked function that is used for showing checkbox checked according to database saved value.
var arr_checked_items = data.data.hobby;
var arraySize = arr_checked_items.length;
$scope.checkItem = function (id) {
var checked = false;
for(var i=0; i<= arraySize; i++) {
if(id == arr_checked_items[i]) {
checked = true;
}
}
return checked;
};
These function work properly on add and edit page, but problem is that when I doesn't apply any changes on checkbox and click on submit button it take blank value.
My question is that: if I does not apply any changes, it should take old value of checkbox and if I apply any changes, it should take new value of checkbox.
Please try with below code. I am not sure weather it is working or not.
$scope.checkItem = function (id) {
var checked = "";
for(var i=0; i<= arraySize; i++) {
if(id == arr_checked_items[i]) {
checked = "checked";
}
}
return checked;
};
I have a dynamic form with a select dropdown, and I want to know what select was changed, however any time that I add a new form and try to change any select the alert is the same: "origen1"
Here is my js code:
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var etiquetas = new Array();
var origenes = new Array();
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a label dynamically
var etiqueta = document.createElement("input");
etiqueta.setAttribute("name", 'etiqueta' + count);
etiqueta.setAttribute("value", "etiqueta");
etiqueta.setAttribute('disabled', true);
etiquetas.push(etiqueta);
//create a select dynamically
var myarray=new Array(3)
myarray[0] = "Opt1"
myarray[1] = "Opt2"
myarray[2] = "Opt3"
var origen = document.createElement("select");
origen.setAttribute("name", 'origen' + count);
for (i=0; i<3; i++)
{
opt = document.createElement('option');
opt.value = i;
opt.innerHTML = myarray[i];
origen.appendChild(opt);
}
origen.onchange = function(){testselect(this);};
origenes.push(origen);
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(etiqueta);
eleDiv.appendChild(origen);
eleDiv.appendChild(eleBtn);
}
function testselect(seleccion)
{
alert(seleccion.name);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
And the html:
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px">
</div>
<input type="submit" value="Submit"/>
</form>
Try inspecting the drop down using firebug. With that you might be able to get the name and ID of the selected drop down but remember the selected drop down has to be selected using firebug in order to see the ID or name used with it.
Since this is JS and the drop down is not selected properly you might not see the name or id used.
So make sure to it is properly selected
I am trying to load the first available option to the third drop-down.
The code is as below.
var categories = [];
categories["startList"] = ["C.","C#.","D.","Eb.","E.","F.","F#.","G.","Ab.","A.","Bb.","B."]; // Level 1
categories["C."] = ["C","C7","Cm","Cm7","Cmaj7","Csus4","Caug","Cdim"];
categories["C"] = ["032010","335553","133211","543210",""];
var nLists = 3; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function init() { fillSelect('startList',document.forms[0]['List1']);
fillSelect('startList',document.forms[0]['List4']);
fillSelect('startList',document.forms[0]['List7']);
}
navigator.appName == "Microsoft Internet Explorer"
? attachEvent('onload', init, false)
: addEventListener('load', init, false);
function getValues() {
var str = '';
for(i = 1; i < 6; i++) {
document.createElement('select')
str += document.getElementById('List' + i).value+'\n';
document.getElementById('creation').innerHTML=""; }
}
<select name='List4' id="List4" onchange="fillSelect(this.value,this.form['ch2'])"><option selected></option></select>
<select name='ch2' id="ch2" onchange="fillSelect(this.value,this.form['tb2'])"><option selected></option></select>
<select name='tb2' id="tb2"><option selected></option></select>
<input id="f2" type="text" size="1" value=1 class=copystuff>
<button onclick="do2()">Do2</button><br>
Now the problem is that when I try to select the second drop down menu "ch2", I want the first value to be loaded automatically in the third dropdown "tb2" according to the selection that I make in the second menu. For eg, if I select C. in the first menu, C in the second menu, I want 032010 to be already selected in the next menu. Is there any simple way to do this?
I have changed your code up a good bit. But I think it's a bit more readable, and may be easier to extend to more forms, categories, and selects.
First here is the working JSFiddle: http://jsfiddle.net/z1sw2bfq/
Second, here is the Fiddle code. Please see the comments for additional context.
<script>
//create a blank object to hold the select lists
var lists = { };
//create an object to hold the categories text arrays
var categories = {
"startList": ["C.","C#.","D.","Eb.","E.","F.","F#.","G.","Ab.","A.","Bb.","B."], // Level 1
"C.": ["C","C7","Cm","Cm7","Cmaj7","Csus4","Caug","Cdim"],
"C": ["032010","335553","133211","543210",""]
};
function init() {
//load the SELECT element from the form into lists
//Get all of the selects in forms[0]...
var selects = document.forms[0].getElementsByTagName("select");
for (var i in selects) {
//...and load those into lists.
lists[selects[i].id] = selects[i];
//Ex: creates a property like "lists.List4" also referenced by "list['List4']")
// which equals the select element with id List4
}
//enter the list name and the select id
fillSelect('startList', 'List4');
}
function fillSelect(currCatName, currListName){
//get the category
var cat = categories[currCatName];
//verify the category is valid
if (cat) {
//get the select
var select = lists[currListName];
//verify the select is valid
if (select) {
//clear the select
for (var i = select.options.length-1; i>=0; i--)
select.remove(i);
//check the data-first attribute
var datafirst = select.getAttribute("data-first");
if (datafirst == "blank") {
var opt = document.createElement('option');
opt.value = "";
opt.text = "";
select.add(opt);
}
//load the select
for (var j in cat) {
var opt = document.createElement('option');
opt.value = cat[j];
opt.text = cat[j];
select.add(opt);
}
}
}
}
//best to use feature detection instead of browser detection
if (window.attachEvent)
window.attachEvent('onload', init, false);
else
window.addEventListener('load', init, false);
</script>
<form action="#" method="get">
<!--
I added a "data-first" attribute to the selects. This will be used to determine if the
first option in the select is a blank or the first item in the list.
-->
<select name='List4' id="List4" onchange="fillSelect(this.value,'ch2')" data-first="blank"></select>
<select name='ch2' id="ch2" onchange="fillSelect(this.value,'tb2')" data-first="blank"></select>
<select name='tb2' id="tb2" data-first="first"></select>
</form>
im trying to select club and display image and return price using radio buttons.
Im stuck because I cannot get the pictures to display. any ideas what could i add?
<label>Select Club:</label><br>
<UL>
<label class="radiolabel"><input type="radio" name="SelectedJersy" value="MUFC" onclick="displayJersy()"> MUFC-(15€)</label><br>
<label class="radiolabel"><input type="radio" name="SelectedJersy" value="MCFC" onclick="displayJersy()"> MCFC-(20€)</label><br>
</UL>
<div id='jersy'></div>
<script type="text/javascript">
var img_Jersy = new Array();
img_Jersy["MUFC"]= "<img src='data/images/MUFC.png'>";
img_Jersy["MCFC"]= "<img src='data/images/MCFC.png'>";
var jersy_prices = new Array();
jersy_prices["MUFC"]=15;
jersy_prices["MCFC"]=10;
function displayJersy()
{
var jersyPrice=0;
var theForm = document.forms["tshirtform"];
var selectJersy = theForm.elements["SelectedJersy"];
for(var i = 0; i < selectJersy.length; i++)
{
//if the radio button is checked
if(selectJersy[i].checked)
{
jersyPrice = jersy_prices[selectJersy[i].value];
//imgJersy = img_Jersy[selectJesry[i].value];
imgJersy = img_Jersy[selectJesry[i].value];
document.getElementById("jersy").innerHTML =imgJersy;
document.getElementById('jersy').style.visibility="visible";
break;
}
return jersyPrice;
}
</script>
I see a couple issues. You forgot a closing curly brace in your for loop.
There's a typo here:
imgJersy = img_Jersy[**selectJesry**[i].value];
Anyway, here's a working version: http://jsfiddle.net/z92togqd/2/