Hello everybody I have a problem with Java Script damned I want to add the values of several variables in one variable and then use this variable, which contains the values of variables You can see the following example HTML Code <input type="text" name="txt1" /> <br/>age <input type="text" name="txt2" /> <br/><br/> <input type="button" name="submits" value="send"/> PHP: Javascript Code field = document.getElementsByName('txt1')[0]; field2 = document.getElementsByName('txt2')[0]; submit = document.getElementsByName('submits')[0]; data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; document.getElementsByName('submits')[0].onclick = function(){ alert(data); } PHP: After executing this code I find that the variables are not displayed values As in the following picture I want to know what the cause of this problem ?
<script type='text/javascript'> function doStuff() { field = document.getElementsByName('txt1')[0]; field2 = document.getElementsByName('txt2')[0]; submit = document.getElementsByName('submits')[0]; data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; alert(data); } </script> ... <input type="button" name="submits" value="send" onclick="doStuff()" /> Code (markup): But I think it would be neater to use IDs and getElementById instead.
Hi! I Agree With "Cash Nebula": Use getElementById. e.g: <br/>Name: <input type="text" name="txt1" id="txt1" /> <br/>Age: <input type="text" name="txt2" id="txt2" /> <br/><br/> <input type="button" name="submits" id="submits" value="send" onclick="setvalues();"/> <script> function setvalues() { field = document.getElementById("txt1"); field2 = document.getElementById('txt2'); submit = document.getElementById("submits"); data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; alert(data); } </script> Code (markup):
It is a valid point that you should be using getElementById... but the reason why your code is not working correctly is because the values for field, field2 and data are being set when the document is loaded and do not change when the submit button is clicked. But, you should steer clear of using inline JS whenever possible, so you were right in that sense. It is also good practice to declare all of your variables (using 'var'). so if you still want to use getElementsByName then the code would be: var submit = document.getElementsByName('submits')[0]; var field = document.getElementsByName('txt1')[0]; var field2 = document.getElementsByName('txt2')[0]; submit.onclick = function(){ var data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; alert(data); } Code (markup): but I would still recommend using the getElementById function.