...

View Full Version : Accessing Form Data jquery and javascript differences



earth2mac
09-12-2008, 07:42 PM
I'm new to dynamic forms. Is there a difference in accessing form elements between javascript and jquery?

For example, I heard the <input> and <textarea> tags for javascript use the "name" or "id" attribute -- which one? Is it the same for jquery?

rangana
09-13-2008, 01:43 PM
The differ but not totally.

In JS, you can access an elements ID via id, name or class attribute.


In JS, to access an element with ID is:


<script type="text/javascript">
window.onload=function(){
document.getElementById('myid').value='I see some trash.';
}
</script>
<input type="text" id="myid">


...while in jquery, it's:


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){$('#myid').value='I see some trash.';});
</script>
<input type="text" id="myid">


In JS, you can access an element using the class attribute by:


<script type="text/javascript">
window.onload=function(){
for(var i=0,myid=document.getElementsByTagName('input');i<myid.length;i++)
if(myid[i].className.toLowerCase()=='myid')
myid[i].value='I see some trash.';
}
</script>
<input type="text" class="myid">


...while using jquery is:


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){$('.myid').value='I see some trash.';});
</script>
<input type="text" class="myid">


To access the name attribute via JS could be:


<script type="text/javascript">
window.onload=function(){
document.getElementsByName('myid')[0].value='I see some trash.';
}
</script>
<input type="text" name="myid">


or


<script type="text/javascript">
window.onload=function(){
document.myform.myid.value='I see some trash.';
}
</script>
<form name="myform">
<input type="text" name="myid">
</form>


...while using jquery is:


<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){$("input[name='myid']").val('I see some trash.');});
</script>
<input type="text" name="myid">



For further reading:
http://docs.jquery.com/Selectors

Hope that makes sense.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum