Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form HTML not getting updated.

Here's something weird

<form>
    <input type="text" id="test" value="abc" />
    <input type="submit" />
</form>

<script>
$('form').submit(function(ev){
   ev.preventDefault();
   alert($(this).html()); 
});
</script>

http://jsfiddle.net/F6XvW/

I change the value of the input field, then click submit to get the HTML, but the value is not updated inside the HTML? What's up with that? How to get the updated HTML?

like image 314
thelolcat Avatar asked Apr 21 '26 12:04

thelolcat


2 Answers

What the user inputs is never changing the HTML. It's a form value which will be sent as a parameter to the server.

See here: your jsfiddle updated:

<form>
    <input type="text" id="test" placeholder="abc" />
    <input type="submit" />
</form>
<script>
$('form').submit(function(ev){
   ev.preventDefault();
   alert('inputted value = ' + $(this).find('input[type=text]').val()); 
});
</script>

If you really want to update the DOM, you have to manually set it: http://jsfiddle.net/F6XvW/3/

JS

$('form').submit(function(ev){
   ev.preventDefault();
   $('#test').attr("value", $('#test').val());
   alert('changed input value to: ' + $(this).find('input[type=text]').val()); 
});
like image 111
Seika85 Avatar answered Apr 24 '26 01:04

Seika85


Changing the input of a value does not change the Document Object Model (DOM).

SOLUTION

$('form').submit(function(ev) {
    ev.preventDefault();
    var newinputval = $(this).find('input[type=text]').val();
    var newhtml = $(this).html();
    newhtml = newhtml.replace("abc", newinputval);
    alert(newhtml);
});

As you see I first receive the new input value, then I get the HTML and replace the DOM's value with the current input value. Now it does exactly the thing that you want.

JSFiddle demo

like image 23
Daan Avatar answered Apr 24 '26 01:04

Daan



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!