Reputation: 19
How can I get the value of the textbox?
<input class="num1" type="text" val=""><br>
<button class="show">Click</button>
this is my Js code:
var value = $('.num1').text();
$('.Click').click(function(){
$('<'p>').text(value);
});
when I clicked the "click" button I want to show in a paragraph the text that I'd input to the textbox.
Upvotes: 0
Views: 413
Reputation: 2424
In your code there is an error: if you want to catch the click event you should use the class of the button. Another error in your code is about the single quotes you use to insert value into the <p>
. And remember, is $('p')
, not $('<p>')
.
The code should look like that:
$('.show').click(function(){
$('p').text(value);
});
You can use this code:
jQuery
$(function(){
$("form").on("submit", function(event){
event.preventDefault();
var text = $(".num1").val();
$("#outputText").text(text);
})
});
Your HTML should be something like that:
HTML
<form>
<input class="num1" type="text" val="">
<button class="show">Click</button>
</form>
<p id="outputText"></p>
Note that in this case is really important to stop the default event behavior using preventDefault().
If you are not using a form the previous code became something like that:
jQuery
$(function(){
$(".show").on("click", function(event){
var text = $(".num1").val();
$("#outputText").text(text);
})
});
HTML
<input class="num1" type="text" val="">
<button class="show">Click</button>
<p id="outputText">
</p>
The outputText
div is a div I've created to show the text.
I've prepared jsfiddle1, jsfiddle2 you can use to see the code in action, I hope it helps ;-)
Upvotes: 3
Reputation: 7117
$('.show').click(function () {
var value = $('.num1').val();
$('p').text(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="num1" type="text" val=""></input>
<button class="show">Click</button>
<p></p>
There are type mistakes
var value = $('.num1').val();
should be in click
method.val()
instead of .text()
to get the input value.Upvotes: 1
Reputation: 2157
use .val()
not .text()
$(".show").click(function(){
var value= $(".num1").val();
$(".para").text(value)
});
Upvotes: 1
Reputation: 336
Use the val()
operator on the input to get the value, and then you could use the following code:
Html:
<input class="num1" type="text">
<button class="show">Click</button>
<p class="output"></p>
Javascript:
$('button').click(function(){
$('.output').html($('.num1').val());
});
Upvotes: 1
Reputation: 4288
Use .val()
for form elements to retrieve or set its value. Also, care with typo when you set the paragraph text.
var value = $('.num1').val();
$('.show').on('click', function(){
$('p').text(value);
});
Upvotes: 3