I have a form and it works fine (it is to save on a table of a database the name of the item and it's value), now I'm on the visual thing of this form and I want to activate a submit input when another field is not empty.
The submit input starts with the propperty disabled="true"
and I created a function to active it with JS and I show you'll the resume of the code I have.
<html>
<head>
<script>
function value(e) {
if (window.event) {
keynum = e.keyCode;
} else {
keynum = e.which;
}
if ((keynum > 47 && keynum < 58) || (keynum == 8) || (keynum
== 13) || (keynum == 46)) {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<form>
.
.
<input type="text" name="price" id="price" onkeypress="return
value(event);" onkeyup="activateBTN()" required>
...
<input type="submit" name="register" value="register"
id="btn_submit" disabled="true">
</form>
</body>
</html>
I don't know what is wrong with the btn
variable or if is other the propperty I should use instead disabled
.
Any idea of what's wrong on the code?
CodePudding user response:
I would suggest you to try to create an full example. It would be way easier to understand how to help you.
In any case you are were really close. But you should set btn.disabled
to false
(instead of "false"
which translated to a truthy value)
Working example here:
function activateBTN() {
var aux = $('#price').val();
if (aux.length > 0) {
$("#btn_submit").prop('disabled', false);
} else {
$("#btn_submit").prop('disabled', true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="price" id="price" onkeyup="activateBTN()" required>
<button disabled id="btn_submit"> submit </button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
EDIT 1:
Or, since you use jquerry anyway, you can replace your javascript with this:
function activateBTN() {
var aux = $('#price').val();
if (aux.length > 0) {
$("#btn_submit").prop('disabled', false);
} else {
$("#btn_submit").prop('disabled', true);
}
}
EDIT 2: or go with @esqew option for javascript :D
CodePudding user response:
@Berci's answer definitely satisfies your requirements, but you can also use Element.setAttribute()
and Element.removeAttribute()
in this context to add/remove the disabled
attribute from the DOM:
function activateBTN() {
var aux = $('#price').val();
var btn = document.getElementById('btn_submit');
if (aux.length > 0) {
btn.removeAttribute('disabled');
} else {
btn.setAttribute('disabled', '');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="price" id="price" onkeyup="activateBTN()" required>
<button disabled id="btn_submit"> submit </button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>