I have a text field
text_field_tag('version',version, :cols => 20 , :onchange => "validateVer(this);")
In validateVer java script function I am checking whether a valid float is entered, if not I am returning by default 1.0. How can I return the previous value in text field(version).
One way to do this is to store the last valid value in a data-
attribute:
// modify your validateVer function to return false if validation fails and true otherwise
function validateVer(elem) {
}
function changeIfValid(elem) {
if (validateVer(elem)) {
$(elem).data('last-valid-version', $(elem).val());
} else {
var lastValidVersion = $(elem).data('last-valid-version');
if (lastValidVersion != null) {
$(elem).val(lastValidVersion);
} else {
$(elem).val('1.0');
}
}
}
And change your text field to call changeIfValid
for the onChange
event:
text_field_tag('version',
version,
:cols => 20,
:onchange => "changeIfValid(this);")
EDIT: In order to initialize data-last-valid-version
or set any of the other attributes for the text_field_tag
, you can just pass it as a hash value to the text_field_tag
method:
text_field_tag('version',
version,
:cols => 20,
"data-last-valid-version" => "A_DEFAULT_VAL",
:onchange => "changeIfValid(this);")
By the way, data-*
attributes are a feature of HTML 5 not Rails. Even if you are using HTML 4 or XHTML, jQuery can still handle them for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.