Reputation: 6351
I have a button (named Benjamin):
<input type="submit" name="btn_submit" value="Next →" />
And on a click event it says 'Loading' and does cool stuff. However, if there is a problem, I want it to change back to its original text while displaying the error message elsewhere.
$('input[name=btn_submit]').click(function() {
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val('Next →');
return false;
});
Somehow, the literal text →
is applied to the button, rather than the cool →. How do I fix this?
Upvotes: 1
Views: 754
Reputation: 207501
$("input[name='btn_submit']").click(function() {
var elem = $(this);
elem.data( "orgText", elem.val() ).val('Loading');
window.setTimeout(
function(){
elem.val( elem.data("orgText") );
}, 1000 );
return false;
});
Upvotes: 0
Reputation: 413720
if you know the code for the character, you can add it to a JavaScript string with .fromCharCode()
:
var s = "hello " + String.fromCharCode(1023); // just a made-up number
You can also embed characters in JavaScript strings if you know their hex code:
var s = "string \u1023 string";
Upvotes: 0
Reputation: 18546
Html is evaluated with different rules that JavaScript is. Html entities only parsed by the html parser. Either use the unicode literal, like so:
$(this).val('Next \u2192');
Or better, keep track of the original value and then set it back:
var initalButtonValue = $(this).val();
$(this).val('Loading');
// Stuff
$(this).val(initialButtonValue);
Or perhaps even better, use HTML data attributes to store the states.
<input type="submit" name="btn_submit" value="Next →" data-normal-value='Next →' data-loading-value='Loading...' />
Then:
// Set to loading
$(this).val($(this).data("loading-value"));
// and back to normal
$(this).val($(this).data("normal-value"));
Upvotes: 3
Reputation: 76003
How about storing the value of the element with $.data()
and retrieving it later:
$('input[name=btn_submit]').click(function() {
$.data(this, 'value', this.value);
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val($.data(this, 'value'));
return false;
});
Here is a demo: http://jsfiddle.net/39thm/ (the setTimeout
is just for demonstration)
Docs for $.data()
: http://api.jquery.com/jquery.data
Also you are using thr $(this)
selector more than once, if you use it a bunch then it's a good idea to cache the selection:
$('input[name=btn_submit]').click(function() {
var $this = $(this);
$.data(this, 'value', this.value);
$this.val('Loading');
// Logicy Stuff...
// Error?
$this.val($.data(this, 'value'));
return false;
});
Upvotes: 0
Reputation: 318498
Put the actual → character in there instead of a HTML entity. Using an entity only works if you set HTML content - and form values are not HTML at all.
When using it inside <input value="...">
it only works because in this case the entity is replaced while the HTML is parsed, so the value gets the actual character.
Upvotes: 1