user4595064
user4595064

Reputation:

Can't change form input value using JavaScript

I'm trying to implement a simple anti-spam field on my form where the server generates a random string, sends it to the user, and then JavaScript reverses the string before submitting it. If the string doesn't match, the submission is discarded as spam. The issue is that I can't seem to get JavaScript or jQuery to reverse the input value.

   $(document.ready(function() {
    var reverse = $('#simple').val().split("").reverse().join("");
    document.getElementById('simple').setAttribute('value', reverse);
}))

Using

$('#simple').val(reverse);

instead of the setAttribute method also fails.

The input field itself is:

        <input type="text" id="simple" name="simple" value="abcde" />

jQuery is being included and I can get the input value to reverse if I type in the same code via the developer tools console, but the page itself doesn't work. Thanks!

Upvotes: 1

Views: 6801

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388316

You have an error, in the document ready callback, other than that it is fine

$(document).ready(function() {
  //      ^ need to close the parenthesis here 
  var reverse = $('#simple').val().split("").reverse().join("");
  $('#simple').val(reverse)
    //or document.getElementById('simple').setAttribute('value', reverse);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="simple" name="simple" value="abcde" />

Upvotes: 2

itzMEonTV
itzMEonTV

Reputation: 20349

$('#simple').val(reverse); should work if id simple is unique.(no other objects with same id). Also you can use $('input[name=simple]').val(reverse);

Check this jQuery change input text value

Upvotes: 0

void
void

Reputation: 36703

$(document.ready(function() {
    var reverse = $('#simple').val().split("").reverse().join("");
    document.getElementById('simple').value =  reverse;
});

Upvotes: 1

user2116780
user2116780

Reputation:

var test= document.getElementById("mytext");
test.value = "My default value";

Upvotes: 0

Related Questions