I am learning jQuery. I am no ninja at it. After reading the following tutorial at W3Schools, I wanted to try something difficult. So I modified their sample a little bit wrote this :
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
for(i=1;i<7;i++) // Getting the values from the input boxes
{
var a[i] = $("#test"+i).val();
}
for(i=1;i<7;i++) //printing the values in the document
{
document.write("<p>"+a[i]+"</p>");
}
});
});
</script>
</head>
<body>
<p>Name: <input type="text" id="test1" value="Mickey Mouse"></p><br>
<p>Name: <input type="text" id="test2" value="Mickey "></p><br>
<p>Name: <input type="text" id="test3" value="Mouse"></p><br>
<p>Name: <input type="text" id="test4" value="Micse"></p><br>
<p>Name: <input type="text" id="test5" value="Mice"></p><br>
<p>Name: <input type="text" id="test6" value="use"></p><br>
<button>Show Value</button>
</body>
</html>
Here in the line var a[i] = $("#test"+i).val();, is this possible. I mean using “+” sign for identifying the id. ?
The code is not working. It should show all the inputs made in the fields on the html page. But it is not showing any response. Is there any mistake I made which jQuery doesn’t support?
First, you need to declare
aoutside of the for loop as an array. This will allow your code to work as-is, however you will lose all of your html.To avoid losing all of your html, add a div to your html that will contain the output, for example,
then replace your document.write with
$("#output").append("<p>" + a[i] + "</p>");However, you still have two for loops, you could reduce it to one like this:
That’s good, but we’re not done yet. $(“#output”) is a relatively expensive method call, we can reduce to only making it once rather than seven times by caching it in a variable and reusing it:
Now the code runs quickly and efficiently, however if we ever added another input, we would have to increase the magic number (
7) by 1. Why not instead just loop over the inputs?You could do even more by moving the .append to outside of the each loop, however that will not make a significant difference in this case compared to the additional code it would require.