Check if textbox is empty before executing jQuery
This may be a very simple question, but I find it confusing.
How do I run myFunc () if textField_1
not empty?
Excicute .on('click', '#openButton', myFunc)
if ($('#textField_1').val()!="")
?
+3
Fergoso
source
to share
3 answers
Check inside the handler:
.on('click', '#openButton', function() {
if( !$('#textField_1').val().trim().length ) myFunc(); //thanks to @Mike for the suggestion on trim and length, see comments
})
+5
tymeJV
source
to share
See below code
<div>
<div>
<input type="text" id="text"/>
<input type="button" value="click" id="click"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#click").click(function () {
if ($("#text").val() != '') {
myfunction();
}
});
});
function myfunction() {
alert($("#text").val());
}
</script>
0
Rithik
source
to share
You can check $('#textField_1').val()
in the instructions if
. If empty, it will be treated as false
, otherwise, it will be treated as true
.
JS (jQuery):
$('#openButton').on('click', function () {
if ($('#textField_1').val()) {
myFunc();
}
});
Here's a fiddle .
0
flowstoneknight
source
to share