Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner HTML with input values

have a brief question regarding innerHTML and input values that have been entered. See the brief example below (using jQuery for convenience):

http://jsfiddle.net/F7urT/2/

jQuery:

jQuery(document).ready(function($) {
    $('.send').click(function() {
        alert( $('.content').html() );
        return false;
    });
});​

html:

<div class="content">
    <input type="text" name="input" value="Old Value" />
    <input type="button" class="send" value="Send" />
</div>​

If you edit the input value, then click the 'Send' button, the alert shows that the innerHTML gotten contains the input with the "Old Value", rather than the value the user has entered. Why is this? And how can we get the HTML as a string with user entered input values?

like image 275
Matthew Ruddy Avatar asked Nov 30 '22 23:11

Matthew Ruddy


2 Answers

this solution is better. works for more inputs.

  $('input[type=text]').attr('value', function (i, val) { return val; });
  $('input[type=checkbox],input[type=radio]').attr('checked', function () { return this.checked; });
  $('textarea').html(function () { return this.value; });
  $('select').find(':selected').attr('selected', 'selected');
like image 36
DanCZ Avatar answered Dec 04 '22 11:12

DanCZ


The new value is stored as a property not an attribute, the value can be obtained by inputelement.value, modifying the value does not affect the attribute. If you want the html with the new value just set the attribute to the new value.

For check boxes and radio buttons set the checked attribute, set the innerHTML for text areas, for selects set the selected attribute on the option

http://jsfiddle.net/mowglisanu/F7urT/5/

like image 106
Musa Avatar answered Dec 04 '22 10:12

Musa