Reputation: 67
I'm currently attempting to get my Javascript code to mesh with HTML written by someone else. The goal is to get the header to change by using jquery by typing it into a text input box and then clicking on a button.
Not exactly sure why it isn't working. In my mind it seems as if it should be functioning properly. If someone could help find a correct solution and explain to me why mine isn't working it would be much appreciated.
(HTML shortened)
<tr> <td colspan=2 align=right> Title:<input type=text id=newTitle value="Picture Title"> </td> <td> <button id=genTitle>Change Title</button> </td> </tr>
<h2 id=artTitle align=center>Picture Title</h2>
(javascript)
var newTitle = $('#newTitle').val();
$( "#genTitle" ).click(function() {
$( "#artTitle" ).text(newTitle)
})
Upvotes: 1
Views: 5905
Reputation: 93
Here is the working example for you.
$( "#genTitle" ).click(function() {
var newTitle = $('#newTitle').val();
$( "#artTitle" ).text(newTitle)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<tr>
<td colspan=2 align=right> Title: <input type=text id="newTitle" value="Picture Title"> </td>
<td> <button id="genTitle">Change Title</button> </td>
</tr>
<h2 id="artTitle" align="center">Picture Title</h2>
Upvotes: 0
Reputation: 3148
The value must be extracted inside the click
.
So the Javascript code becomes:
$( "#genTitle" ).click(function() {
var newTitle = $('#newTitle').val();
$( "#artTitle" ).text(newTitle)
})
Upvotes: 0
Reputation: 36703
See this. (I hope you have the correct html, make sure to have all the quotes and doublequotes wrapped around every attribute properly.)
// Set a event on button click
$("#genTitle").click(function(){
// Fetch Input Value
var val = $("#newTitle").val();
// Set the value fetched as the html of header
$("#artTitle").html(val);
});
Upvotes: 4