I want to have form fields, when populated and a button clicked will change the contents of span's within html. I have tried the following but the span contents aren't being replaced.
I have written the following html:
<form role="form">
<div class="form-group">
<label for="name">
Name
</label>
<input type="text" class="form-control" id="nameValue" />
</div>
<button id="generate" type="submit" class="btn btn-default">
Generate Story
</button>
</form>
<p>The persons name is <span id="name"></span></p>
Then have written the following jQuery:
<script>
$(function() {
$("button").click( function()
{
$("#nameValue").keyup(function() {
var val = $(this).val();
$("#name").html(val);
});
}
);
});
</script>
Try separating keyup
, click
event handlers , setting button
disabled
to true
if no value at "#nameValue"
, setting button
disabled
to false
at keyup
event
$(function() {
var button = $("button"),
val = "";
$("#nameValue").keyup(function() {
val = $(this).val();
if (val.length > 0 && /\w+/.test(val)) button.prop("disabled", false)
});
button.click(function(e) {
e.preventDefault();
$("#name").html(val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form role="form">
<div class="form-group">
<label for="name">
Name
</label>
<input type="text" class="form-control" id="nameValue" />
</div>
<button id="generate" type="submit" class="btn btn-default" disabled="true">
Generate Story
</button>
</form>
<p>The persons name is <span id="name"></span>
</p>