Tuesday 11 July 2017

JQuery - Alter Value in Input Without Using Class or ID

In this example we have the following html code:

<!DOCTYPE html>
<html>

<body>
<h1>Please Give Us Money</h1>
<p>Donate Below</p>

<input name="donation" value="0.00" maxlength="6" size="3" type="text">
</body>
</html>


Because the input doesn't have a class or id, we have to locate our target by making use of some of the informaiton we do know. In this case, we will use the 'name' of the input. The following code will change the 'value' from 0.00 to 3.00 for any input on the page which has a 'name' of 'donation':

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
       $('input[name="donation"]').attr('value', '3.00');              
    });
</script>


If the input did have an id (or class, although id is more appropriate) this would be a lot simpler. The HTML line would look like this:

<input id='donate' name="donation" value="0.00" maxlength="6" size="3" type="text"> 

and the JQuery would look like this:

$('#donate').attr('value', '3.00');  

There are, no doubt, many other ways to achieve this but this is the way i found worked best for me.

No comments:

Post a Comment