14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4 ■ HTML <strong>and</strong> <strong>JavaScript</strong><br />

Figure 4-12. Depending on <strong>JavaScript</strong> availability, the user gets a link or a button to send the form<br />

However, the function has one major flaw: it will fail when there are more input elements following the Submit<br />

button. Change the HTML to have another input after the Submit button:<br />

<br />

<br />

Name:<br />

<br />

<br />

<br />

<br />

<br />

email:<br />

<br />

<br />

<br />

You will see that the "send" Submit button does not get replaced <strong>with</strong> a link. This happens because you removed<br />

an input element, which changes the size of the array, <strong>and</strong> the loop gets out of sync <strong>with</strong> the elements it should reach.<br />

A fix for this problem is to decrease the loop counter every time you remove an item. However, you need to check<br />

whether the loop is already in the final iteration by comparing the loop counter <strong>with</strong> the length of the array (simply<br />

decreasing the counter would cause the script to fail, because it tries to access an element that is not there):<br />

function submitToLinks()<br />

{<br />

var inputs,i,newLink,newText;<br />

inputs=document.getElementsByTagName('input');<br />

for (i=0;i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!