I've seen plenty examples of people disabling buttons if textboxes are empty but I haven't found any which will disable a button for only certain textboxes. I'm new to Jquery and I know it is pseudo coded but you can get the idea. Which Jquery function do I have to call so that it is constantly checking? And how can I use an or statement in the if clause to determine if any textbox field is empty?
if( $('#txtEvent').val.length === 0 || $("#txtID").val.length === 0)
{
$('#btnSave').attr("disabled", "disabled");
}
else
{
$('#btnSave').attr("enabled", "enabled");
}
Form Controls
<asp:TextBox ID="txtEvent" runat="server"></asp:TextBox>
< asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server"" Text="Save and Next" />
You can do it two different ways:
if (!$("#txtEvent").val()) { //undefined will yield false
//call a method! .val() not .val
$("#btnSave").attr("disabled", "disabled");
} else {
$("#btnSave").attr("enabled", "enabled");
}
Or:
if ($("#txtEvent").length > 0) {
$("#btnSave").attr("disabled", "disabled");
} else {
$("#btnSave").attr("enabled", "enabled");
}
If you want these constantly running, wrap them in:
$("#txtEvent").on("change", function() { //code });
//using the onchange event will trigger the code whenever the txtbox changes.
//you can also use onblur if you want it to trigger AFTER the txtbox loses focus
Please note you'll have to convert these into proper asp code! This is simply a logistical answer.
Try
var $empties = $('#txtEvent, #txtID').filter(function(){
return $.trim($(this).val()).length == 0
})
$('#btnSave').prop("disabled", $empties.length === 0);
Even though this is two years old question, I would like to show another way using bind. See the text 'keyup mouseup cut paste'
This will also work if you cut or paste text as well as keyboard input. Also this will work if we click the little cross in the text box to clear the text( using mouseup).
OP stated that disable a button for "only certain textboxes".
Say we have following text boxes
<input type="text" name="tbox1" id="txtbox1" />
<input type="text" name="tbox2" id="txtbox2" />
<input type="text" name="tbox3" id="txtbox3" />
<input type="text" name="tbox4" id="txtbox4" />
<input type="submit" id="btnSubmit" name="button" value="Save and Next" disabled />
If we need to enable/disable the button based on values entered in to txtBox1 OR txtBox3 then we can use this
<script>
$(document).ready(function() {
$("#txtbox1, #txtbox3").bind('keyup mouseup cut paste', function () {
var txt = $(this);
setTimeout(function () {
$('#btnSubmit').prop('disabled', $(txt).val() == '');
}, 100);
});
});
</script>
If we need to enable/disable the button only when both txtBox1 AND txtBox3 are not empty then we can use this
<script>
$(document).ready(function() {
$("#txtbox1, #txtbox3").bind('keyup mouseup cut paste', function () {
setTimeout(function () {
($('#txtbox1').val() && $('#txtbox3').val()) ? $('#btnSubmit').prop('disabled', false) : $('#btnSubmit').prop('disabled', true);
}, 100);
});
});
</script>
Related
When I click this button, it runs the function and all is well.
<input id="input_listName" /><button id="btn_createList">add</button>
when I click it, it runs this:
$('#btn_createList').click(function(){
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
});
When I press it, it appends the value in the input to the <li> element.
How do I redo this so that instead of running function on click, the function runs when I click the 'enter key'?
I'd like to hide the submit key all together. Please note, there are no form tags around input and submit, as this is an API app and I'm just trying to filter and not really submit anything.
Don't.
You have a form. Treat it as such.
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listName.value = ""
}, false);
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like required to the <input /> element, and the browser will handle it all for you.
I think what you want is a check for which key was pressed, correct?
To do that, you simply need to check for
event.keyCode === 13
So your code would be something similar to the following:
$('#btn_createList').keypress(function(event){
if (event.keyCode === 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
Hopefully that does the trick!
With the help of the event, you can catch the pressed enter (keycode = 13) key, as in my example.
Was it necessary?
$('#btn_createList').keypress(function(event){
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
<input id="input_listName" /><button id="btn_createList">add</button> this syntax is technically wrong, your tag is starting with <input> and ending with </button>. Also you can add a simple check to your function that if user haven't entered anything into the input field that should return nothing.
you can also have a look at this cheat sheet to know more about keycodes https://css-tricks.com/snippets/javascript/javascript-keycodes/
$('#btn_createList').keypress(function(event){
if($('#input_listName').val()) {
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
}
});
<div id="btn_createList">
<input id="input_listName" type="text">
<ul class="ul_current">
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
I am trying to enable img button in while typing in textbox. But it is working after lost focusing from textbox. How can see changes immediately?
$("[id$='txtNewPass2']").change(function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
Use the keyup input event.
$("[id$='txtNewPass2']").on('input', function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
The reason for recommending a keyup as opposed to a keydown is that in the below snippet, if you use a keydown the event will always be one letter behind.
Update:
After playing around with the example I created below. I can see that the input event creates a much smoother update effect. See the example below to see how all three work comparitively
Sample:
$('#keyup-input').on('keyup', function () {
$('#keyup-div').html($('#keyup-input').val());
});
$('#keydown-input').on('keydown', function () {
$('#keydown-div').html($('#keydown-input').val());
});
$('#input-input').on('input', function () {
$('#input-div').html($('#input-input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Keyup:</h1>
<input id="keyup-input" type="text" />
<div id="keyup-div"></div>
<br/>
<br/>
<h1>Keydown:</h1>
<input id="keydown-input" type="text" />
<div id="keydown-div"></div>
<br/>
<br/>
<h1>Input:</h1>
<input id="input-input" type="text" />
<div id="input-div"></div>
#James123 I hope it will work as you want.I just used Input event instead of change
$("[id$='txtNewPass2']").on("input",function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
I want my form to meet a set of criterias before the submit button gets enabled, my form is in this order:
Text field, value has to be over 150
Set of radio selects, 1 has to be selected
TOS box, has to be checked
So far I have this:
if ((parseInt($('#amount').val(), 10) > 149) && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
{
// Enable Button here
}
Do I have to add this to everything I'm checking, for example keyup on the textfield, change on the select and checkbox and set true in variables that those fields are "OK" or how do I do it ?
You need to create a custom validate function, which you have to run onchange of your text field, and on click of your radio and checkbox click event.
Following psudo code might help you.
var textFieldValidationPassed = false;
function validateFormFields() {
//First checks if text field length is not less then 150.
// then check if one of the radio button is selected.
// then check for TOS box checked state;
if (textFieldValidationPassed && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
// enable submit button;
}
}
$('input:radio[name="radioset1"]', 'input.checkbox_check').click(function() {
validateFormFields();
})
$('#amount').keyup(function(){
if($(this).val().length > 149) {
textFieldValidationPassed =true;
validateFormFields();
}
})
it is a workaround but will work, make submit button initially...
$(":submit").on('focus',Validate);
function Validate(){
if ((parseInt($('#amount').val(), 10) > 149) && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
{
// Enable Button here
}
else
{
//Disable button
}
}
You can just add click, change events at once like this
$("input").on("change, click", function(){
});
Write your logic within this.
Also you've checkbox validation wrong. Check box will be clicked.
$('input.checkbox_check').prop('checked')
Here is the complete code
$(function(){
$("input").on("change, click", function(){
if ((parseInt($('#UserName').val(), 10) > 149) && $('input:radio[name="gender"]').is(':checked') && $("#remember").prop('checked'))
{
$("#submit").removeAttr("disabled");
}
else{
$("#submit").attr("disabled", "disabled");
}
});
});
WORKING FIDDLE
You can use jQuery.validate. You can define custom validation methods too.
http://jqueryvalidation.org
You can use HTML5 validation. For example:
<input type="checkbox" required name="checkbox1" />
<input type="text" min="150" name="input1" />
You can see another example here http://www.w3schools.com/html/html5_form_attributes.asp
You can call it at textbox, radiobutton and checkbox onchange events.
EDIT:
$(document).ready(function () {
$("input").change(function () {
//call function.
});
});
I am using following script to bind a keypress event on each textbox so that on reaching the maxlength, focus will switch to next input field. Passing classname as the prarameters to the function.
function autoFocusPhoneFields(txtbox1ID,txtbox2ID) {
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
$(this).bind('keypress', function(){
if(this.value.length == $(this).attr('maxlength')) {
$(this).next('input').focus();
}
});
});
}
$(document).ready(function(){
autoFocusPhoneFields('mobileprefix','mobilecode');
});
As i have mentioned two different input ..it is runnign fine. Butis there any way around so that it will get the classnames and runs through each input box to attach keypress event.
If I understand you correctly, you want to attach the same event handler to every input field? Just use the selector:
$(':text')
(for all input type="text") fields.
So just change
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
to:
$(':text').each(function() {
If I get you correctly you just need to use type selector for input. You can also get rid of calling each to iterate thru inputs since binding event to multiply elements interates via them. So you can change your code into something like following:
var autoFocusPhoneFields = function () {
$('input:text').keypress(function() {
if(this.value.length == $(this).attr('maxlength'))
$(this).next('input').focus();
});
}
$(autoFocusPhoneFields);
This works fine.
HTML
<input id="one" class="inp" maxlength="5" />
<input id="two" class="inp" maxlength="3" />
<input id="three" class="inp" maxlength="2" />
JS Part
$(function(){
var onpress = function(){
var val = $(this).val();
var next_input = $(this).next('input');
var mx = $(this).attr('maxlength');
try {
mx = Number(mx);
if (next_input.length >= 1 && val.length >= mx){
next_input.focus();
}
} catch(x){}
}
$('input.inp').bind('keypress', onpress);
});
Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.
This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/
Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});
Did you try out the keydown or keypress event?
I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});
there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>