JavaScript - Problem With Function Accessing A Form Element
Hello
I am fairly new to Javascript. I have a function which takes a string which consists of key value pairs and sets a form control based on key being the form element name and value being the value to set. eg string could be "key1=orange;key2=2;key3=whetever" Here is the function: function processresponse(frm, serverResponse) { var items = serverResponse.split(";"); for(var i = 0; i < items.length; i++) { var item = items[i]; var eqchar = item.search("="); if(eqchar != -1) { var key = item.slice(0, eqchar); var value = item.slice(eqchar+1); var elemname = key; if(document.getElementById(elemname) != null) { var type = frm.elements[elemname].type; if (type=="checkbox") { value == "1" ? frm.elements[elemname].checked=true : frm.elements[elemname].checked=false; } else if (type=="text"){ //do processing for text (text input) frm.elements[elemname].value = value; } else if(type=="select-one"){ //only one is openformmode - default to [0] - true if(value == "0" || value.length == 0) { frm.elements[elemname].options[0].selected = true; } else { frm.elements[elemname].options[1].selected = true; } } else { alert("unknown ctrl type: " + type + " name: " + frm.elements[elemname].name + " val: " + value + " key: " + key); } } //if(frm.getElementById(elemname) } } } The problem line is: var type = frm.elements[elemname].type; elemname is case sensitive so if for example the form element is called dog and the string elemname is Dog, then the line fails with Error: 'elements[...].type' is null or not an object So my check if(document.getElementById(elemname) != null) is insufficient to guard against this. I realise I could do a try catch but there must be a more legant way than that. How can I test the formname more reliably? Any ideas would be very welcome. Angus Similar TutorialsI am very new to javascript. I have a problem getting to any element from this form generated by the jsp page using struts. Please show me how to get to item[0].totalAmount for example, so that I can create a function to calculate the calculateTotal(). So far, when I do the alert, it is only valid up to document.myForm.item; the document.myForm.item[0] is invalid according to the alert. Any help is very much appreciated. function calculateTotal(){ alert(document.myForm.item); } <form name="myForm" method="post" action="/myAction.do"> <table id="display" border="1"> <tr> <th scope="col" id="totalAmount">Total Amount</th> <th scope="col" id="adjustmentAmount>Adjustment Amount</th> <th scope="col" id="newAmount">NewAmount</th> </tr> <tr> <td><input type="text" name="item[0].totalAmount" id="totalAmount" value="100" readonly="readonly"></td> <td><input type="text" name="item[0].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[0].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> <tr> <td><input type="text" name="item[1].totalAmount" id="totalAmount" value="350" readonly="readonly"></td> <td><input type="text" name="item[1].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[1].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> </table> </form> Hi, I know this isn't in the context of the rest of the code but hoepfully it's enough to go on. Is anyone able to tell me why the following works in FireFox but not IE - Code: var DateTextBox; function WindowPostBack(newdate) { window.DatetextBox.SetDate(newDate); } and the following works in IE but not FireFox - Code: var DateTextBox; function WindowPostBack(newdate) { window[DatetextBox.id].SetDate(newDate); } FireFox doesn't recognise 'id', IE seems to require it. I need it to be supported in both so I've put in a check to see which browser the code is currently dealing with and used both snippets in an if/else but it seems to me that something so straightforward shouldn't require this and I am missing something obvious. Hopefully some wiser heads than mine can help me out with this. Many thanks in advance for any responses... I've read through the past threads and did not find anything that quite matched my problem, which surprises me because I thought it would be fairly common. Anyway, I have a script where I define an array and populate the array. In the same script is a function that tries to scan the table looking for a match with the value in a global primitive. In the HTML, a button click invokes the function. But while the function can correctly access the global primitive, it simply stops running when it encounters the reference to the global array. Here's a shortened, simplified snippet of the code: [code] <script type="text/javascript"> var len = 2; var course_code = new Array(); course_code[0] = "A010"; course_code[1] = "A500"; function runcodes() { alert('In runcodes'); alert('len = '+len); alert('course_code.length = '+course_code.length); for (i = 0 ; i < course_code.length ; i++) {alert(course_code '+i+' = '+course_code[i]);} } </script> <body> <button type="button" name="runc" id="runc" onclick="runcodes()"; > Click to display course codes table. </button> </body> [ICODE] When I bring this up in a browser and click the button, I get the following alerts: In runcodes len = 2 and then the script simply stops. So it stops on the first reference to the array. Clearly I am getting to function, and the function is able to handle the global primitive 'len', but it stops on encountering the global array. I've tried a lot of variations on the the theme, but nothing gets past this restriction. How do I access elements in a global array from inside a function? i have this code: PHP Code: <?php foreach ($freechat_list as $r) { $uniqueCode = substr($r,0,12); $id = substr($r,13); $blocked_record = RcBlockListTablePeer::isBlocked($id,$requestor_id); ?> <a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $id."/".$blocked_record; ?>)"><?php echo $uniqueCode; ?></a> } then i have my JS: [CODE] thank you all but i am totally confused now...here is my full code: <?php foreach ($freechat_list as $r) { $uniqueCode = substr($r,0,12); $id = substr($r,13); $blocked_record = RcBlockListTablePeer::isBlocked($id,$requestor_id); ?> <a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $id."/".$blocked_record; ?>)"><?php echo $uniqueCode; ?></a> } my JS: Code: function viewornot(id) { alert(id); } alert(id) only gives me the id but in my href i concatenated it with blocked_record: viewornot(<?php echo $id."/".$blocked_record; ?>) please help? What I am trying to achieve, is a button that calls a function that changes the onclick attribute of that button, so that when it is clicked again, it resets the onclick attribute to call the default function. here is what the stripped down code looks like: Code: <html> <head> <script type="text/javascript"> function remove_prep(a){ a.value="cancel"; a.onclick="cancel_remove(this);"; } function cancel_remove(a){ a.value="remove"; a.onclick="remove_prep(this);"; } </script> </head> <body> <input type="button" value="remove" onclick="remove_prep(this);" /> </body> </html> for some reason, it only fires once, after which it ceases to work properly. thanks for the help this part of my code is killing me. Hi, firstly I apologise if the title of this thread isn't quite accurate. I'm sure you've all heard it before but I am a complete newbie to Javascript so again: apologies if this is boring and tiresome to even read, let alone help with! I have been asked to make some changes to a form that uses Javascript for the form validation. There is a 'function' that contains the variables of the various form fields and then further code to raise 'alerts' if one of the fields on the form hasn't been filled in. My problem is that for some reason I am unable to add an extra variable to this code after the field of 'County' (this will hopefully make sense when you see the code / link...) and I am stumped as to why. I am able to add variables for all of the other required fields except for 'Postcode' after 'County'. This is the case for both forms. The link is he http://samdelara.co.uk/previews/banq...ation-form.htm and the code I am trying edit is below: function checkAvailibility() { // re-calculate... calculate (); if ( isName() && isAddress1() && isTown() && isCounty() && isPostcode() && isYourEmail() && isFuncDate() && somethingToQuoteFor() && isYourEmailValid() ) { document.ordersummary.emailQuote.value = "No"; setValue(); return true; } else { return false; } } function isName() { if (document.ordersummary.Name.value=="") { alert ("\n Please Enter Your Name") document.ordersummary.Name.focus(); return false; } return true; } function isAddress1() { if (document.ordersummary.Address1.value=="") { alert ("\n Please Enter Your Address") document.ordersummary.Address1.focus(); return false; } return true; } function isTown() { if (document.ordersummary.Town.value=="") { alert ("\n Please Enter Your Town") document.ordersummary.Town.focus(); return false; } return true; } function isCounty() { if (document.ordersummary.County.value=="") { alert ("\n Please Enter Your County") document.ordersummary.County.focus(); return false; } return true; } function isPostcode() { if (document.ordersummary.Postcode.value=="") { alert ("\n Please Enter Your Postcode") document.ordersummary.Postcode.focus(); return false; } return true; } function isYourEmail() { if (document.ordersummary.YourEmail.value=="") { alert ("\n Please Enter Your Email") document.ordersummary.YourEmail.focus(); return false; } return true; } function isFuncDate() { if (document.ordersummary.FuncDate.value=="") { alert ("\n Please Enter Your Function Date") document.ordersummary.FuncDate.focus(); return false; } return true; } function isemailonly() { if (document.ordersummary.emailonly.value=="") { alert ("\n Please Enter Your Email Address") document.ordersummary.emailonly.focus(); return false; } return true; } Any help with this would be very much appreciated and once again, I apologise for my distinct lack of knowledge in this area! Sam Hi I have a large'ish project under development. The code below distills the problem I am having. In essence, I am trying to read in an XML file. It appears to load okay but when I try to count how many there are of a certain tag (The "Team" tag) I am told that there are zero. This is despite being told that that file loads okay (as the callback function is called). Javascript and the xml file is below. I hope that it is easy to follow. When the page is loaded, the initialize function is called. I first check my browser as I only need this to work on a Mozilla browser (I am using Mozilla Firefox 3.6.3). I then load the xml file and the callback function (fileLoaded) is called. I then try to find out how many "Team" tags I have, but get the message that there are zero. Sorry if this is a simple question but I have spent the best part of yesterday trying to get this to work. Any help would be appreciated. Thx G === javascript === Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script type="text/javascript"> // Global variable so that everything can access it var xlmDoc; function initialize() { // This function gets called when the page loadds browserCheck(); xmlDoc=document.implementation.createDocument("", "doc", null) xmlDoc.load("small.xml"); // This file is shown at the end of this document, but it is a separate xml document xmlDoc.onload = fileLoaded; } // End of initialize function fileLoaded() { // Called when file is loaded (this does get called as expected) alert("File loaded"); var teams = xmlDoc.getElementsByTagName("Team"); var count = teams.length; alert("no of Teams: " + count); // This displays zero - WHY??? } // End of fileLoaded function browserCheck() { // START: This function just checks that I am using a Mozilla browser (I am) var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined'); if(moz) { alert("Mozilla"); } else {alert("Not Mozilla"); } } // End of browserCheck </script> </head> <body onload="initialize()"> </body> </html> === xml file === Code: <Root> <Team> <Type>GLF</Type> <Name>Verulam</Name> <Postcode>AL1 1JG</Postcode> <Page>693</Page> </Team> <Team> <Type>RFU</Type> <Name>London Manx RFC</Name> <Postcode>AL1 2DJ</Postcode> <Page>704</Page> </Team> <Team> <Type>RFU</Type> <Name>University of Hertfordshire RFC</Name> <Postcode>AL10 9AB</Postcode> <Page>729</Page> </Team> </Root> Hello Pros. I am having a problem with getting id of the active element which calls function savePanelPosition(), as a result, I cannot get a new location of this element and pass it to my Page Method SaveCoords() All draggable panels are created dynamically in code-behind. Please, see the javascript code below. Any ideas/help are greatly appreciated function pageLoad() { var Max = "<%=qtyMax%>"; for (i = 0; i < Max; i++) { $find('DragP' + i).add_move(savePanelPosition); } } function savePanelPosition() { var elem = document.activeElement; var loc = $common.getLocation(elem); PageMethods.SaveCoords(elem, loc.x, loc.y); /* there is a call to PageMethods.SaveCoords(), but elem = objectHTMLBodyElement, loc.x=0, loc.y =0 */ } Hello, all. I have a script that toggles an element's style between display block and display none based on an onclick event. It's being implemented in a content management system (WordPress) so it has some dynamic post ID's assigned to it. I have tried editing it to toggle the variable "type" so that I can have the class of the div change with the rest of the variables being swapped during the toggle, but no matter what I've changed I can't seem to get it to update the variable when someone clicks on the link with the onclick event. Everything else works perfectly, content is shown and hidden when you click the link, I just can't get the "type" variable to switch. I think it's something to do with the JavaScript function itself (it looks to me like it's only looking at 4 variables and this new one would be a new variable that's being toggled). Below is the code. How can I get the type variable to update like the others (hidden_css, tmp_text, more_text, less_text)? Code: /*-----------------------------------------------------------------------------------*/ // Show Hide Posts /*-----------------------------------------------------------------------------------*/ ### Function: Enqueue JavaScripts add_action('wp_enqueue_scripts', 'showhide_scripts'); function showhide_scripts() { wp_enqueue_script('jquery'); } ### Function: Short Code For Inserting Show/Hide Into Post add_shortcode('showhide', 'showhide_shortcode'); function showhide_shortcode($atts, $content = null) { // Variables $post_id = get_the_id(); // Extract ShortCode Attributes extract(shortcode_atts(array( 'type' => 'show', 'more_text' => __('View Full Post'), 'less_text' => __('Close Post'), 'hidden' => 'yes' ), $atts)); // Determine Whether To Show Or Hide Content $hidden_css = 'display: none;'; if($hidden == 'no') { $hidden_css = 'display: block;'; $type = 'hide'; $tmp_text = $more_text; $more_text = $less_text; $less_text = $tmp_text; } // Format HTML Output $output = '<div id="'.$type.'-content-'.$post_id.'" class="'.$type.'-content" style="'.$hidden_css.'">'.$content.'</div>'; $output .= '<div class="'.$type.'-link"><a href="#" onclick="showhide_toggle(\''.$type.'\', '.$post_id.', \''.esc_js($more_text).'\', \''.esc_js($less_text).'\'); return false;"><span id="'.$type.'-toggle-'.$post_id.'">'.$more_text.'</span></a></div>'; return $output; } ### Function: Add JavaScript To Footer add_action('wp_footer', 'showhide_footer'); function showhide_footer() { echo '<script type="text/javascript">'."\n"; echo '/* <![CDATA[ */'."\n"; echo 'function showhide_toggle(a,b,c,d){jQuery("#"+a+"-content-"+b).toggle();jQuery("#"+a+"-toggle-"+b).text(jQuery("#"+a+"-toggle-"+b).text()==c?d:c)};'."\n"; echo '/* ]]> */'."\n"; echo '</script>'."\n"; } I need to highlight rows in a dropdownlist. I need to do this inside a function. I have a textbox filled with the indexes of the rows which need to be highlighted - e.g. by changing the background colour to blue. This is my function: function HighlightSelection() { var myList = document.getElementById('dropdown'); var myString = document.getElementById('textbox').value; var listitem; if (myString.length>0){ var mySplitResult = myString.split(";"); var thisInx; for (i = 0; i < mySplitResult.length; i++) { thisInx = mySplitResult[i] listitem = myList.options[thisInx]; // listitem.style.color='red'; } } } the index (thisInx) is correct - but setting its color does not work. I have the following form working with on onsumbit function, but I would like to change it so that instead of having to click the purchase button to see total price, you only have to change the quanity text box input. I would welcome any help. I just can not seem to get it to work. Code: <script language="javascript" type="text/javascript"> function checkQuantity(frm) { var succesful = false; var numQuantity; numQuantity = parseInt(frm.Quantity.value); var numTotalPrice; if (numQuantity != 0) { numTotalPrice = numQuantity * 4; frm.TotalPrice.value = numTotalPrice; //new String(numTotalPrice); successful = true; } else { alert("Sorry must order more than 0"); successful = false; } return succesful; } </script> Code: <form action="" onsubmit="return checkQuantity(this)" style="width: 193px"> <table cellpadding="4" style="width:111%"> <tr> <td class="style1"> Quanity:</td> <td class="formInputCell"> <input name="Quantity" type="text" style="width: 55px" /></td> </tr> <tr> <td class="style1"> Total Price $ </td> <td class="formInputCell"> <input name="TotalPrice" type="text" style="width: 55px" /></td> </tr> <tr> <td class="style2"></td> <td><input id="Submit1" type="submit" value="Buy Now" class="buttonstyle" /></td> </tr> </table> </form> I am trying to have it so that when someone choose a value from the select box, it then displays it in the html. The problem is im not very good with javascript, and my error keeps coming up as undefined where as before it was coming up as "[object HTMLSelectElement]". Can anyone tell me whats up? PHP Code: <html> <head> <script type="text/javascript"> function moveValue() { var no=document.getElementById("no"); var option=no.options[no.selectedIndex].numberr; document.getElementById('numberr').innerHTML = option; } </script> </head> <body> <form> Select numbers:<br /> <select id="no"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> </select> <input type="button" onclick="moveValue()" value="-->"> <i id="numberr">Testing</i> </form> </body> </html> and now that i look at it, i suspect that the reason that it is not working is that i should have "ID"'s or value's on each of the options but i do not know for certain Hello All, I am fairly new to javascript. I need to access a button on a form and perform task using onclick. When I view the source of the page, the id of the button seems to be dynamic with a 'Link' suffix. (ex. xtydLink). How can I access this button if I cannot use getelementbyid because the ID changes? Thanks in advance Can someone see what is wrong with this code: Code: frm=document.createElement('form') frm.action="/cgi-sys/formmail.pl" frm.method="POST" fld=document.createElement('textarea') fld.appendChild(document.createTextNode(simpleCart.items)) frm.appendChild(fld) It is supposed to dynamically create a textarea and fill it up with the return of simpleCart.items() Hi! I have this form that depending on the shift you choose certain form elements get grayed out. Here's the part that I don't understand. I validate the form in php and display the errors but the form re-enables everything that was grayed out. Not the behavior I was expecting. How would I go about this? I attached a copy of the HTML source created from php. I'm grateful for any help! Thanks! Hi all, At work I have written a form builder which is all drag and drop. The issue I have is with ending the drop, I have no problems in IE. The drag is controlled by the onmousemove and onmouseup events for the document body. The trouble is, in Firefox, if the cursor is over a form item, then the onmouseup event doesn't fire and therefore the drag doesn't end. There is no problem with other items, other HTML items, tables, list, divs, then all bubble the event to the body. Anyone ever come across this, if so how did you get round it. Do I need to manually make form elements bubble in Firefox? Maybe I should just stick a div opacity 0 over the drag objects and make that call the body's onmouseup event. Any thoughts much appreciated, Cheers, Dale is there a way to shorten something like: document.scoresheet["HomeTotalHCaps"].value to a simple short name like var1.value ? Hi, I'm trying to automatically generate a new <option> tag in a html form using the below code, but it's not working. Does anyone have any ideas? The get_lightboxes function is being called via the add_to_lightbox functon. Javascript: function get_lightboxes(title, new_lightbox_id){ var new_option = document.createElement('option'); new_option.text = title; new_option.value = new_lightbox_id; var select_box = document.getElementByID('lightbox_select'); try { select_box.add(new_option, null); } catch(ex) { select_box.add(new_option); } } HTML: <form method="post" action="<?=$_SERVER['PHP_SELF']?>" name="lightbox_form" onsubmit="add_to_lightbox('<?=$_GET['id']?>', '<?=$_GET['media_urn']?>', lightbox_select_<?=$_GET['id']?>.value); return false;"> <input type="hidden" name="submitted" value="1" /> <input type="hidden" name="user_email_<?=$_GET['id']?>" value="<?=$_GET['user_email']?>" /> <input type="hidden" name="record_id_<?=$_GET['id']?>" value="<?=$_GET['id']?>" /> <input type="hidden" name="media_urn_<?=$_GET['id']?>" value="<?=$_GET['media_urn']?>" /> <h2>Add/Delete from existing lightbox:</h2> <p> <select name="lightbox_select_<?=$_GET['id']?>" id="lightbox_select"> <? foreach ($get_lightboxes as $lightbox) : ?> <? $lightbox_id = $lightbox["lightbox_id"]; ?> <? $title = $lightbox["title"]; ?> <? if(strlen($title) > 25) $title = substr($title, 0, 25) . "…"; ?> <option value="<?=$lightbox_id?>"><?=$title?></option> <? endforeach; ?> </select> <input type="submit" name="submit" value="Add" /> </p> </form> Hi people, I'm a novice in javascript and have no clue how to get get the following logic through in a form. Any help will be greatly appreciated. I have searched the forums and looked at a few similar script but can't make out head and tail of it Sorry if this is a oft repeated question. Here is the form I need, the post method is email : Name (txtfield) DOB (Date) Address (txtarea) Programme (Select list) : Options : Programme1, Programme2, Programme3 Date (Select list) : options : 10/10/2009 to 12/09/2009 15/10/2009 to 16/10/2009 Venue : Mainland Harvey Waterloo Time : 9am - 12 noon 1 pm - 3 pm 3 pm - 5 pm Here is the Logic : Date : Conditions If Programme1 is selected then date options 10/10/2009 to 12/09/2009 and 15/10/2009 to 16/10/2009 should both be selectable. If Programme2 is selected then date options 10/10/2009 to 12/09/2009 and 15/10/2009 to 16/10/2009 should both be selectable. If Programme3 is selected then date option 15/10/2009 to 16/10/2009 should auto selected and greyed out so that user don't have to select this. Venue : Conditions If Programme = Programme1 then all the venues should be selectable. If Programme = Programme2 and date = 10/10/2009 to 12/09/2009 then all the venues should be selectable. If Programme = Programme2 and date = 15/10/2009 to 16/10/2009 then only venues Harvey and Waterloo should be selectable. If Programme = Programme3 and date = 15/10/2009 to 16/10/2009 then only venue Waterloo should be selectable.... in fact venue Waterloo should be auto selected and greyed out so that user cannot change it. Time :Conditions : Always should be default selection and greyed out If Programme = Programme1 and venue is any one of Mainland, Harvey, Waterloo then the time should default to 9 am - 12 noon. If Programme = Programme2, Date = 10/10/2009 to 12/09/2009 and venue is any one of three then, the time should default to 1 pm - 3 pm. If Programme = Programme2, Date = 15/10/2009 to 16/10/2009 and venue is one of Harvey or Waterloo then the time should default to 1 pm - 3 pm If Programme = Programme3, Date = 15/10/2009 to 16/10/2009 and venue = Waterloo then the default time should be 3 pm to 5 pm Sorry for the long post and so many conditions. I'm trying to get a hang of how to go about doing this. This looks a pretty complicated logic but if you can point me in the right direction I'm sure I will get my head around this. Thanks for having a look and thanks in advance for any help. Cheers In fact: does input type=image belong to the form's elements collection, in ECMAScript ? It looks like not. When traversing the form's elements collection with classical javascript (document.forms[formname].elements), an input type="image" is not included. Is this an inheritance from old browsers interpretors? Does anyone know the reason for this omission? |