Skip to content Skip to sidebar Skip to footer

.val() And .text() Don't Work?

I want to email div contents via php and form tag. I have 2 divs with these classes: .simpleCart_items .simpleCart_total I want to fetch contents from these divs and insert their

Solution 1:

It must be something else in your HTML or script that you are showing us because when I set up a simple test using your code, it works fine here: http://jsfiddle.net/jfriend00/7q6DP/.

This works perfectly fine for me (in Chrome, Firefox, Safari and IE):

HTML:

<buttonid="submitForm">Submit</button><divclass="simpleCart_items">simpleCart items text</div><divclass="simpleCart_total">simpleCart total</div><textareaid="itemsinfo"style="width:320px height:160px"></textarea><br><inputtype="text"id="totalprice"/>

Javascript (after page is loaded):

$('#submitForm').click(function(){
  var items = $('.simpleCart_items').text();
  var tprice = $('.simpleCart_total').text();
  $('#itemsinfo').val(items);
  $('#totalprice').val(tprice);
});

Please show the rest of your code and HTML.

The things to check are:

  1. Are there any javascript errors showing in the error console or in the debugger console?
  2. Are you initializing your event handlers after the page has loaded?
  3. Do any javascript errors show in the debug console when you press the submit button?
  4. Is your submitForm event handler getting called? If you set a breakpoint or put an alert in their, does it get hit?
  5. Can you set a breakpoint in your submit handler and see what's happening with the values of items or tprice?
  6. Make sure your class names don't have the leading period on them when you put them in your HTML. It should be class="simpleCart_items", not class=".simpleCart_items".

Solution 2:

Your code works just fine when I put it in a page:

http://jsfiddle.net/Guffa/krYQh/

When you click the submit button, the fields are populated with the data. (I added a return false in the submit event handler just to keep the form from posting.)

Some possible errors in your code:

  • You have used class=".simpleCart_items" instead of class="simpleCart_items".
  • The form doesn't have id="shopform".
  • You have use the ids shopform, itemsinfo or totalprice on any other elements.

Solution 3:

I guess you should use ".html()" instead of ".text" something like below.

  $('#shopform').submit(function(){   
  var items = $('.simpleCart_items').html();   
  var tprice = $('.simpleCart_total').html();   

    $('#itemsinfo').html(items);   
    $('#totalprice').val(tprice); 
  });

Solution 4:

I suppose you should use .innerHTML instead of .text()

Solution 5:

You should be able to use the .val() to get the value for the text areas instead of using .text().

Try using alert(items); before you set the div's contents just to make sure you are actually getting data.

Post a Comment for ".val() And .text() Don't Work?"