Reputation: 13
I am having a problem where I need to change the HTML inside of a <button></button>
. Here are the relevant lines of HTML:
<input class="form-control" type="text" id="subject" />
<button type="button" class="btn" id="btv"><p>Text 1</p></button>
<button type="button" class="btn" id="btc"><p>Text 2</p></button>
And this is the jQuery:
$('.btn').click(function(){
var text = $('.btn p').html();
$('#subject').val(text);
});
All I have managed to do is make the first text show no matter which button I press. I really need a bit of help.
Upvotes: 1
Views: 495
Reputation: 72299
First of all paragraph
inside button
in not valid HTML
.
But in this case also you can make your code working through the use of $(this)
along with .children()
like below:-
$(document).ready(function(){
$('.btn').click(function(){
$('#subject').val($(this).children('p').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control" type="text" id="subject" />
<button type="button" class="btn" id="btv"><p>Text 1</p></button>
<button type="button" class="btn" id="btc"><p>Text 2</p></button>
Note:-
Make sure that jQuery library added before your script code.
If you are adding your script code on top of page then it should be wrapped inside $(document).ready(function(){..});
, but if you are adding script code at the bottom of the page then it's not necessary (in both case jQuery library need to be added before code)
A valid HTML example is like below:-
$('.btn').click(function(){
$('#subject').val($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="form-control" type="text" id="subject" />
<button type="button" class="btn" id="btv">Text 1</button>
<button type="button" class="btn" id="btc">Text 2</button>
</body>
Upvotes: 3
Reputation: 15685
$('.btn').click(function(){
var text = $(this).html();
$('#subject').val(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="form-control" type="text" id="subject" />
<button type="button" class="btn" id="btv">Text 1</button>
<button type="button" class="btn" id="btc">Text 2</button>
</body>
Upvotes: 1
Reputation: 1668
Use text and context
$('.btn').click(function(){
$('#subject').val($(this).text());
});
Upvotes: 0