Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text to a paragraph using .val()

Tags:

jquery

input

I am trying to change the text inside a paragraph whenever a submit button is clicked. For some reason it doesn't work. I tried finding answers in other questions but couldn't. Why isn't this working?? Javascript code:

var $submit = $('input:submit');
$submit.click(function(){
    var $newText = $('input:text').val();
    var $p = $('#newStatus');
    $p.text($newText);
});

Html:

<div class = "grid_12">
  <form>
    <input type="text" name="status">
    <input type="submit" name="submit" value = "Post">
  </form>
  <p id = "newStatus"></p>
</div>

Thanks!

like image 911
nevos Avatar asked Jun 02 '26 08:06

nevos


2 Answers

That's because the form is submitted, prevent the default action of the event:

$submit.click(function(e){
   e.preventDefault();
like image 59
undefined Avatar answered Jun 05 '26 01:06

undefined


Try this:

var $submit = $('input:submit');
$submit.click(function(){
    var $newText = $('input:text').val();
    var $p = $('#newStatus');
    $p.text($newText);
    return false;   // prevent form from being submitted
});

Actually your forms gets submitted, so we need to stop that.

FIDDLE DEMO

like image 24
palaѕн Avatar answered Jun 05 '26 00:06

palaѕн



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!