JavaScript - Save Undefined Value From Checkbox
Hi..
I have checkbox and I need to get his value. I create function for checkbox if checkbox is clicked it is true then the checkbox value is H else W. Code: function chk(){ if(document.getElementById('H').checked==true){ var H = document.getElementById('H'). value = H; } else if(document.getElementById('H').checked==false){ var H = document.getElementById('H'). value = W; } } and I have function for save : Code: function ApproveLeaveOP(){ var H = document.getElementById('H').value; document.sampleform.action="AddLeave.php?H="+H; document.sampleform.submit(); } <input type="checkbox" name="H" id="H" value="" onclick="chk()"> I don't know how can I add value to the checkbox if I click the value will be H if not the value is W. I am new in using checkbox. Thank you so much.. Similar TutorialsI'm trying to find the best approach for saving the checked value of a checkbox in SQL With this script the FieldName "Active" toggles yes/no onClick... That we can post to the database no problem... What I am having trouble with is saving the checked value. I want to make the FieldName Active =hidden, and only display the checkbox with correct value checked yes/no. Code: <script type="text/javascript"> var YesOrNo = (function() { if(document.select.checkbox.checked) { document.select.Active.value = 'yes'; } else { document.select.Active.value = 'no'; } }); </script> <form name="select"> <input type="hidden" name="Active" size="10" /> <input type="checkbox" name="checkbox" onclick="YesOrNo();" value="on" /> </form> I am using a checkbox to turn on and off some labels on a line on a google map, which is working fine if the line is already drawn, using this function: Code: function distboxclick(labelsbox) { if (labelsbox.checked) { for (var i=0; i<distmarkers.length; i++) { if (distmarkers[i].mLabel != null) distmarkers[i].mLabel.show(); } } else { for (var i=0; i<distmarkers.length; i++) { if (distmarkers[i].mLabel != null) distmarkers[i].mLabel.hide(); } } } but the thing is that I want the labels to be turned off to begin with and switched on if the box is checked. Which is also fine, using this snippet: Code: if (prevMarker){ var dist = getSegmentDistance(prevMarker.mMarker, distmarker); var label = new ELabel(point, dist, "labelstyle", new GSize(10,-15)); distmarkers[numMarkers-1].mLabel = label; distlabels.push(label); map.addOverlay(label); label.hide(); drawOverlay(); } but what I am trying to do now is make sure that if the box is checked before the line starts to be drawn then the labels will come up straight away. So I figured all I had to do was add in the following to the above: Code: if (labelsbox.checked){ label.show(); } else { label.hide(); } and pass the labelsbox variable to the function where that is all happening. But instead I get a "labelsbox is undefined" error... If I take that if statement out I see that labelsbox is defined, but that doesn't really help. I guess I'm putting things in the wrong order or something, but I'm kind of baffled. You can see my test page here. Thanks in advance for any suggestions. Hello guys, The following excerpt is part of a very huge project(in terms of code involved). Pardon me if it lacks a bit of context. But I assume I have posted adequate information for understanding the problem. Code: var sztitlebar_specific= "<table cellpadding='0px' cellspacing='0px' width='100%'><tr>" +"<td class='tiletitle'>" "<img src='../images/alert.gif' onclick='toggleAlerts(\"#ID#\")' alt='Toggle Alerts' title='Toggle Alerts' style='cursor: hand'>" + "<input type='checkbox' name='pricesonlycb' onclick='parent.applyFilterPricesOnly(\"#ID#\",pricesonlycb.checked,mypricesonlycb.checked,\"#NAME#\")'>" + "<input type='checkbox' name='mypricesonlycb' onclick='parent.applyFilterPricesOnly(\"#ID#\",pricesonlycb.checked,mypricesonlycb.checked,\"#NAME#\")'>" + "<td class='tiletitle' style='text-align: center'>#NAME#</td>" + </tr></table>"; The onclick event fires without any trouble, and the following function is called. Code: function applyFilterPricesOnly(filterid, pricesonly, mypricesonly,filtername){ alert("applyFilterPricesOnly called: filterid =" + filterid + "filtername =" + filtername + "mypricesonly =" + mypricesonly + " pricesonly=" + pricesonly); } But when I alert the status of the checkboxes they show up as "undefined". As you can see, the first piece of code defines a titlebar with a button and a couple of checkboxes and the name of the titlebar. And it is these checkboxes that remain undefined even though I can see them and check and uncheck them. But the name of the titlebar gets passed to the function correctly when the onclick event fires and it gets alerted. Where am I going wrong? So here's what i want to do: i have 2 checkboxes, when Checkbox A is checked, i want to automatically check the checkbox B. When A is unchecked, then uncheck B how can i do that? thanks a lot ! Hi, If I have two check-boxes and one is already checked and then the is checked, how would I get it to uncheck the first one using JavaScript. Thanks, Cs1h Hey, I'm trying to make a game, I learned how to do so by reading tutorials but the problem is that I do not know how to implement the save/load function into the game, the tutorial surrounding that area was very unclear to me, and here I am... Any tips on how to make this work is greatly appreciated, I wouldn't asked if I hadn't tried my best and every way I could think of. I'm still quite new to coding so... The first piece of code is the game, the second one is what I'm trying to make the game work with. I tried for a while and got the game to reset back to values, but only the values I set in the code so it never actually worked. The tutorial doesn't give any live examples and I really am... not that bright when it comes to coding Sorry and thanks, all inputs are appreciated. I read tutorial from links below, Javascript String Compression | Almost Idle Tutorial for save code Incremental Lesson 9 - For Loops | Almost Idle Tutorial for the game code Code: /*Pleae refer to Lesson 9.txt for a full description on this lesson*/ //The timer to run code every second var Timer = window.setInterval(function(){Tick()}, 1000); var buildings = []; //The object declaration for game saves function GameSave() { this.money = 0; this.buildings = []; for (var i = 0;i < buildings.length;i++) { this.buildings[i] = 0; } } //The object declaration for buildings function Building() { this.Name = "Lemonade Stand"; this.Cost = 10; this.PerSec = 1; } //The function to initialise all buildings function InitBuildings() { LoadBuilding("Lemonade Stand",10,1); } //The function to automatically load a building into the buildings array function LoadBuilding(name,cost,persec) { var cur = buildings.length; buildings[cur] = new Building(); buildings[cur].Name = name; buildings[cur].Cost = cost; buildings[cur].PerSec = persec; } //The function used to gather money function GatherMoney() { game.money++; //++ tells javascript to add 1 to the variable //Display the player's current money document.getElementById("money").innerHTML = game.money; } //The function that gets run every second function Tick() { for (var i = 0;i < buildings.length;i++) { game.money += game.buildings[i] * buildings[i].PerSec; } document.getElementById("money").innerHTML = game.money; } //The function to buy a lemonade stand function Build(id) { if (game.money >= buildings[id].Cost) { //Check if the player has enough money, then subtract it and add a new building if they do game.money -= buildings[id].Cost; game.buildings[id] = game.buildings[id] + 1; document.getElementById("money").innerHTML = game.money; document.getElementById("Building1Qty").innerHTML = game.buildings[id]; } } //Run this code once the page has loaded fully window.onload = function() { InitBuildings(); window.game = new GameSave(); }; Code: /*Pleae refer to Compression.txt for a full description on this lesson*/ function NewGame() { this.name = "Our Game"; this.description = "Our Game's Description"; this.numbers = []; for (var i=0;i<10;i++) { this.numbers[i] = i; } } var Game = new NewGame(); window.onload = function() { var SaveGame = JSON.stringify(Game); SaveGame = encode_utf8(SaveGame); SaveGame = lzw_encode(SaveGame); window.localStorage['SaveName'] = SaveGame; SaveGame = window.localStorage['SaveName']; SaveGame = lzw_decode(SaveGame); SaveGame = decode_utf8(SaveGame); window.GameTwo = JSON.parse(SaveGame); document.getElementById("name").innerHTML = "Name: " + GameTwo.name; document.getElementById("desc").innerHTML = "Description: " + GameTwo.description; var numbers = ""; for (var i=0;i<10;i++) { if (numbers.length == 0) {numbers = i;} else {numbers += ", " + i;} } document.getElementById("numbers").innerHTML = "Numbers: " + numbers; } // LZW-compress a string function lzw_encode(s) { var dict = {}; var data = (s + "").split(""); var out = []; var currChar; var phrase = data[0]; var code = 256; for (var i=1; i<data.length; i++) { currChar=data[i]; if (dict['_' + phrase + currChar] != null) { phrase += currChar; } else { out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0)); dict['_' + phrase + currChar] = code; code++; phrase=currChar; } } out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0)); for (var i=0; i<out.length; i++) { out[i] = String.fromCharCode(out[i]); } return out.join(""); } // Decompress an LZW-encoded string function lzw_decode(s) { var dict = {}; var data = (s + "").split(""); var currChar = data[0]; var oldPhrase = currChar; var out = [currChar]; var code = 256; var phrase; for (var i=1; i<data.length; i++) { var currCode = data[i].charCodeAt(0); if (currCode < 256) { phrase = data[i]; } else { phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar); } out.push(phrase); currChar = phrase.charAt(0); dict['_'+code] = oldPhrase + currChar; code++; oldPhrase = phrase; } return out.join(""); } function encode_utf8(s) { return unescape(encodeURIComponent(s)); } function decode_utf8(s) { return decodeURIComponent(escape(s)); } Reply With Quote 01-16-2015, 05:52 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts the problem is that I do not know how to implement the save/load function into the game save it where? that particular question is important as JavaScript has only limited places where it can save something at all. 1) save it on the server => call a server script with the appropriate data (e.g. via AJAX) 2) cookies, very limited storage space, only works on the same browser 3) WebStorage, more space than cookies, but still only the same browser 4) IndexedDB (same as above) Hello, Is it possible to store the edited value in the div tag in the original file, such that next time i open the HTML file the new edited value appears. Thanks in advance. Have a Good day. Hey Guys, I'm working on a Gameserver for a Game, written in JavaScript. I want to save all console.log()'s with Timestamp into a txt-file but I don't know how :/ Could you help me with it and tell me how I can do this? for example, I want to save User-Logins into the logs. This is the code I'm using right now. Code: case "LOGIN": var data = PacketModels.login.parse(datapacket); User.login(data.username, data.password, data.is_banned, data.is_online, function(result, user){ if(result){ if(user.is_banned == 1){ console.log("[WARNING] ".red + data.username + " tried to login. It failed because the User is banned!"); c.socket.write(packet.build(["LOGIN", "ISBANNED"])); }else if(user.is_banned == 0){ if(user.is_online == 1){ console.log("[WARNING] ".red + data.username + " tried to login. It failed because the User is already online!"); c.socket.write(packet.build(["LOGIN", "ALREADYLOGGEDIN"])); }else if(user.is_online == 0){ c.user = user; c.enterroom(c.user.current_room); c.user.is_online = 1; c.user.save(); c.socket.write(packet.build(["LOGIN", "TRUE", c.user.current_room, c.user.pos_x, c.user.pos_y, c.user.username])); console.log("[INFO] ".blue + data.username + " has logged in on Map:[" + (c.user.current_room_name).blue + "] X:[" + String(c.user.pos_x).blue + "] Y:[" + String(c.user.pos_y).blue + "]"); } } ... Reply With Quote 12-22-2014, 02:48 PM #2 sunfighter View Profile View Forum Posts Senior Coder Join Date Jan 2011 Location Missouri Posts 4,830 Thanks 25 Thanked 672 Times in 671 Posts JS will not save a text file. You need to do this with a server side language like PHP and if your going to all of that trouble you might want to study a database at the same time or soon after. Hi , i have got this img src html.. how do i write a javascript to auto save this image in C:\ without right click on the image? <img src="/user_images/V/VI/VIR/Virgo001/1135356474_ylittlekid.jpg" alt="1135356474_ylittlekid.jpg"></img> thanks for help! Hello all, i am a newbie here. I am starting to programme with javascript. I am designing a website. in This website there is an input with type = text and beside this input, there is another input with type = submit. If i open this website: The default value on the search text is "Enter a text", and if I click submit button, this button can recognize the value of the search text which is "Enter a text". <input id="searchText" type="submit" value="Enter a text"/> <input id="searchSubmit" type="submit" value="Submit"/> And then i modified a little bit. I have this javascript: var searchInput = $('#searchText'); searchInput.focus( function() { searchInput.attr('value', ''); }); The goal is, when I click on the search text, the default text is gone. And it worked. But if i write a new text on the search text, the submit button still recognized the value of search text as empty string. Can anyone please help me?? Thank you I have a long survey form and once its submitted it gets recorded into a database. I would love to be able to save a PDF version of the HTML form with all their radio buttons and textfields filled out at the same time its submitted. It would need a unique name that matches their record in the database (maybe it pulls the data that was entered into one of the form fields for the name). Whether it gets uploaded to an ftp or just emailed to a mailbox doesn't really matter. The purpose of this is to basically have a visual interpretation of the data by a single user. Is something like this even possible? Hey guys, I think this is some pretty basic JavaScript but I'm not too familiar with the language and would really appreciate some help here. I have an image switcher script setup. Its very basic and changes the image displayed on click of a link. Here is what I currently have: Javascript: Code: <script type="text/javascript"> function changeIt(imageName,objName) { var obj = document.getElementById(objName); var imgTag = "<img src='"+imageName+"' border='0' />"; obj.innerHTML = imgTag; return; } </script> HTML: Code: <div id="image1"> <img src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/49057_100001550995222_9679_q.jpg" border="0" alt="one" /> </div> <br> <a id="one" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/49057_100001550995222_9679_q.jpg','image1');">one</a> <a id="two" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/174411_100002333675750_7453320_q.jpg','image1');">two</a> <a id="three" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/41512_100000999943382_7276_q.jpg','image1');">three</a> <a id="four" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/41477_100001406980454_629_q.jpg','image1');">four</a> <a id="five" href="#" onclick="changeIt('http://www.dead-paramour.org/fans/fanMCR4.jpg','image1');">five</a> Its very basic but does what I want. What I'm attempting to do is store the image selected as a cookie so that when users refresh/navigate to other pages the image stays to the one they selected. Is anyone able to help me out with this? Any help is greatly appreciated. Thanks, Chris im trying to have it save the values in the menu, i was think either cookies or storing it in the .window thing but i am unsure of how to do these, any help would be great. Code: <script type="text/javascript"> function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } <!-- // initialise shortcuts on page load var selectObj1=null, selectObj2=null// global function init() { selectObj1=document.getElementById("select_1"); selectObj2=document.getElementById("select_2"); selectObj2.disabled=true; // ========== end init() ============== // second select box options list var A= new Array() A["remote 1"]=["0","yup","DVD-1"]; A["remote 2"]=["0","VCR-1","DVD-2"]; // // global variables var saveObj=null, indx=null, targetObj=null, selectNo=null; // function process(obj,sNumb) { // disable unused select boxes if(sNumb==1) { selectObj1.selectedIndex="0"; selectObj1.disabled=true; } else if( sNumb==2) { selectObj1.selectedIndex="0"; selectObj1.disabled=true; } // // store selected index indx=obj.options.selectedIndex; // invalid selection if(indx==0){ return; } // --------- // save passed parameters for use after timeout deleay saveObj=obj, selectNo=sNumb; // put object items list into next select box after clearing targetObj=document.getElementById("select_"+selectNo) targetObj.disabled=false; // clear any existing options note that this starts from end of list, not beginning for(var i=targetObj.options.length-1;i>-1;i--) { targetObj.options[i]=null; } // build in short delay here to avoid error in Opera browser setTimeout("finishOff()",50) } // ----------- 50ms delay here -------- // called from timeout in function process() function finishOff() { var obj=saveObj; // from global // fill selectObj options var i, thisItem=0; // build options list switch(selectNo){ case 2 : targArray = A[obj.options[indx].value]; break; } // for(i=0;i<targArray.length;i++) { thisItem=targArray[i]; // syntax is new Option("text", "value", isDefaultSelectedFlag, isSelectedFlag) targetObj.options[i]=new Option(thisItem,thisItem,false,false); } obj.blur(); } // ============ end process() =================== // fires on selecting in third select box function finish() { select("["+selectObj1.value+"] ["+selectObj2.value+"]") } // ------------ // window.onload=init; //--> </script> Hi all, I found this script online that lets users on an iPhone drag boxes around the screen. The problem is that when you reload the page, the boxes are in different positions than what they were before the reload. Like, you would drag the boxes around and then reload the page, but the boxes would be in the default locations. I want the boxes to stay in the same spot that they were the previous time they moved them. Does that make sense? Anyways, here's the example I found online: http://www.manifestinteractive.com/iphone/touch/ Only works on iPad/iPhone/iPod Touch. It uses jQuery too so if you know of any way to do this, that would be excellent. Thanks. I am trying to do this and have some code im working with. I can load the file through a browse button then save it using the existing code. However, I want instead of the browse option to just preload the file into the textarea and then be able to save it. Code: <script language="javascript"> <!--// var oFileSystem; oFileSystem = new ActiveXObject("Scripting.FileSystemObject"); function ShowFile(sFilePath){ frmEditHTML.tarHTMLText.value = oFileSystem.OpenTextFile(sFilePath).ReadAll(); } function SaveAfterEditing(){ var oFile; oFile = oFileSystem.CreateTextFile(frmEditHTML.filPath.value,1); oFile.WriteLine(frmEditHTML.tarHTMLText.value); oFile.Close(); } </script> Code: <form name="frmEditHTML"> <input type="file" name="filPath" onchange="ShowFile(this.value)"> <br><textarea name="tarHTMLText" cols=60 rows=20></textarea><br> <input type="button" value="Save" name="cmdSave" onclick="SaveAfterEditing()"> </form> Hello. I am new to the forums (I just started my Javascript journey last week), and was hoping to get help with something. I am currently developing a page which allows access to music on a server. This music is being streamed, but users are also able to download this music (assuming they have the license to do so). All of the music uploaded is of the .mp3 format, however they have no filetype extensions, and were not named using any particular naming convention. Because of this, I was hoping to change the filename (when a downloaded is initiated) to variables I have stored based on the current song. I am currently simply opening a new page, in Chrome is looks like this: Code: chrome.tabs.create({ "url": song.url }) Hit presents the user with a prompt to save the file, however, its default name is a random alphanumeric string with no extension, as per their file name on my server. Is there an easy way to do this without renaming all the music server side? I do have the variables song.title and song.artist setup! All help is appreciated! Edit: Since this page is only for Chrome users, I listed the code I am using. I understand window.open and was originally using this. It functions the same, and if I need to revert back to using is instead, I shall. This is code use to save XML file using Javascipt but it can't not save full Processing Instruction, example we have PI is <?xml version="1.0" encoding="utf8"> when run the code then PI is saved with <?xml version="1.0"> and sometime it doesn't word. Please help me fix, thanks PHP Code: function SaveXML(xmlDoc,filename) { var outputXML = xmlDoc.xml; var mfObj = new ActiveXObject("Scripting.FileSystemObject"); var absPath = getPath(); var file = mfObj.CreateTextFile(absPath + filename, true); file.Write(outputXML); file.Close(); } function getPath() { var path = document.location; var str = new String(path); var end = str.lastIndexOf("/"); var absolutePath = str.substring(8, end) + "/"; absolutePath = absolutePath.replace(/%20/g, " "); return absolutePath; } Hi.. I'm new in radio button. Now I have to radio button one for H value means half and W for Whole. Now I don't know how can I get the value to save in to my database. here is my code: Code: <input type="radio" name="CHK_LEAVE" id="H" value="H"> <input type="radio" name="CHK_LEAVE" id="W"value="W"> <script> function ApproveLeaveOP(){ var CHK_LEAVE = document.getElementByName('CHK_LEAVE').value; alert (CHK_LEAVE); } </script> I got an error Object Required. I tried this test: Code: function chk(){ if(document.getElementById('H').checked) { alert ('H') }else if(document.getElementById('W').checked) { alert ('W') } } And it works. Now How can I save it to my database I have this code and I need to insert here the code to get the value of radio button that I choose: Code: function ApproveLeaveOP(){ var EMP_NO = document.getElementById('EMP_NO').value; var DATE_LEAVE_FROM = document.getElementById('DATE_LEAVE_FROM').value; var DATE_LEAVE_TO = document.getElementById('DATE_LEAVE_TO').value; var NAME = document.getElementById('NAME').value; var HOURS_LEAVE = document.getElementById('HOURS_LEAVE').value; var Approve = document.getElementById('Approve').value; var TYPE = document.getElementById('TYPE').value; var dateprocess = document.getElementById('dateprocess').value; document.sampleform.action="AddLeave.php?EMP_NO="+EMP_NO+"&DATE_LEAVE_FROM="+DATE_LEAVE_FROM+"&DATE_LEAVE_TO="+DATE_LEAVE_TO+"&NAME="+NAME+"&HOURS_LEAVE="+HOURS_LEAVE+"&Approve="+Approve+"&TYPE="+TYPE+"&dateprocess="+dateprocess; document.sampleform.submit(); } Code: <input type="text" name="EMP_NO" id="EMP_NO" value="{$empno}" size="8" style="background: #e2e2e2" readonly="readonly"> <input type="text" name="NAME" id="NAME" value="{$fullname}" size="35" style="background: #e2e2e2" readonly="readonly"> <input type="text" name="DATE_LEAVE_FROM" id="DATE_LEAVE_FROM" value="{$DATE_LEAVE_FROM}" size="9"> <input type="text" name="DATE_LEAVE_TO" id="DATE_LEAVE_TO" value="{$DATE_LEAVE_TO}" size="9"> {html_options id=TYPE name=TYPE options=$LeaveStatus selected=$TYPE style="width:140px;"} <input type="radio" name="CHK_LEAVE" id="H" value="H"> <input type="radio" name="CHK_LEAVE" id="W"value="W"> <!--<input type="text" name="STATUS" id="STATUS" value="{$STATUS}" size="10">--> <input type="button" name="Approve" value="Approve" id="Approve" onclick="ApproveLeaveOP()"> I need to save in to my database what I choose. Thank you Hi, In Google Chrome the 'chrome.tabs.captureVisibleTab(integer windowId, function callback)' method will return a data URL of the JPEG encoding of the visible area of the captured tab. We want to save that content as image to hard disk without opening/passing the contents into new html page. Does anybody know how it can be done by javascript. Please provide help. Thanks. Hello, i m new Javascript but knows basics of functions etc. ive created a website, which also has field to Submit Email addresses for newsletters.. Now, i have a TextBox (for users to write email addresses) and a Submit button in which i want to call a Javascipt script function which OnClick takes the value(email address) from the textbox and saves it to a .txt file on server. i think i am just missing a single line, the function name which will store the value.. i searched ovr the net but didnt find it.. plz help mee. Thankyou! |