I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO
Related
I have an enabled and disabled state for the submit button on my form.
The conditions are as follows:
If all input fields have been entered and are valid enable the submit button.
If some fields have not been entered do not enable the submit button.
So far the validation is being done within the onkeyup event and is only working for the first input:
//Custom onkeyup validation
onkeyup: function(element) {
//Check if input is empty remove valid class from parent
var formInput = $(element),
formInputParent = $(element).parent('fieldset');
if(formInputParent.hasClass('form--valid') && formInput.val() === "") {
formInputParent.removeClass('form--valid');
}
//Check if all fields are not empty to remove submit--disabled class
var formInputs = $('form').find(':input');
console.log(formInputs);
formInputs.each(function(){
if(formInputs.length > 0) {
formInputs.parents('form').find('.submit-form').removeClass('submit--disabled');
}
});
}
Check here for a DEMO
You would simply construct a blur (or even a keyup) handler function to toggle the button based on the form's validity. Use the plugin's .valid() method to test the form.
$('input').on('blur', function() {
if ($("#myform").valid()) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', 'disabled');
}
});
DEMO: http://jsfiddle.net/sd88wucL/
Instead, you could also use both events to trigger the same handler function...
$('input').on('blur keyup', function() {
if ($("#myform").valid()) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', 'disabled');
}
});
DEMO 2: http://jsfiddle.net/sd88wucL/1/
Source: https://stackoverflow.com/a/21956309/594235
The code below is what I ended up with so far:
$('#formId').on('blur keyup change', 'input', function(event) {
validateForm('#formId');
});
function validateForm(id) {
var valid = $(id).validate().checkForm();
if (valid) {
$('.form-save').prop('disabled', false);
$('.form-save').removeClass('isDisabled');
} else {
$('.form-save').prop('disabled', 'disabled');
$('.form-save').addClass('isDisabled');
}
}
// Run once, so subsequent input will be show error message upon validation
validateForm('#formId');
It uses checkForm() instead of the form() and my disable button has the classform-save
It is based on #Sparky's answer
There is an issue filed on the jquery-validation git repo.
$('form').find(':input').each(function(index, value){
//action for every element
$(value);
});
In this case you can do this that way: (but I dont like this solution)
var areSomeFieldsEmpty = false;
$('form').find(':input').each(function(i, v){
if ($(v).val().length <= 0){
areSomeFieldsEmpty = true;
}
});
if (!areSomeFieldsEmpty){
//unlock form
}
http://jsfiddle.net/89y26/335/
<html>
<form id="form">
name<br>
<input type="text"><br>
Roll Number<br>
<input type="number"><br>
<input id="next" type="submit" disabled="disabled">
</form>
</html>
Initially, I have set submit button disabled and for each change in the input tag I will call a function to validate the form using jquery
$("input[type='text'], input[type='number']").on("input", function () {
validate();
});
function validate(){
var show = true;
$("input[type='text'], input[type='number']").each(function(){
if($(this).val()==''){
show = false;
}
});
if(show){
$('#next').css({cursor:'pointer'})
$('#next').removeAttr('disabled')
}
else {
$('#next').css({cursor:'not-allowed'})
}
}
});
I am having one checkbox and one input text in a row .I want when a user checks the checkbox to diable the text and clear its value.
I tried this one but nothing:
What is wrong?
HTML:
<span style="width: 200px;font-size: 80%;"><input id="chkSendSummary" type="checkbox" name="ctl03$ctl00$ctl00$chkSendSummary" onclick="checkSendSummaryLetter();"></span>
<input name="ctl03$ctl00$ctl00$txtSendSummary" type="text" id="txtSendSummary" class="NormalTextBox" style="width: 170px;">
var chkSendSummaryLetter=document.getElementById('chkSendSummary');
var txtSendSummaryLetter=document.getElementById('txtSendSummary');
if (chkSendSummaryLetter.checked) {
txtSendSummaryLetter.enabled = true;
} else {
txtSendSummaryLetter.value = "";
txtSendSummaryLetter.enabled = false;
}
You've created a custom property enabled, which has no effect on the DOM. Use disabled instead:
if (chkSendSummaryLetter.checked) {
txtSendSummaryLetter.disabled = false;
} else {
txtSendSummaryLetter.value = "";
txtSendSummaryLetter.disabled = true;
}
<script type="text/javascript">
var chkSendSummaryLetter=document.getElementById('chkSendSummary');
var txtSendSummaryLetter=document.getElementById('txtSendSummary');
if (chkSendSummaryLetter.checked) {
txtSendSummaryLetter.value = "";
hide();
}
if
function hide() {
document.getElementById('txtSendSummary').style.display = 'block';
}
</script>
This post already exists: (found in 2 seconds via google)
javascript hide/show element
you could add a parameter within the function to make it have multiple purposes
I would like to disable a submit button until one of a group of radio buttons is selected. I know there are similar questions out there, but none pertain to a dynamically-created group of radio buttons...
Here is what I have.. a script at the top of the page generates a number of buttons given a user upload in a previous view:
var jScriptArray = new Array(#ViewBag.ColNames.Length);
var array = #Html.Raw(Json.Encode(ViewBag.ColNames));
for( var i = 0; i < #ViewBag.ColNames.Length; i++ ) {
jScriptArray[i] = array[i];
}
var length = #(ViewBag.NCols);
$(document).ready(function () {
for (var i = 0; i < length; i++) {
$('#radioGroupBy').append('<input id="grp' + i +'" type="radio" name="group" value="'+i+'">'+jScriptArray[i]+'</input>')
$('#radioGroupBy').append('<p style="padding:0px;margin:0px;"></br></p>');
}
});
This works, and selecting any of the buttons returns the proper value; great. However, I want to disable the submit button until one of these radio buttons is selected. Using an answer I found on SO earlier, I created the following (this works, but only if I hard code the group of buttons. The issue is it won't work with the Javascript-created group):
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
Also, for the sake of thoroughness, here is the submit button:
<input id="submitbtn" name="submitbtn" type="submit" value="Drill Down" disabled="disabled" />
Thanks so much!
Event delegation (also, use .prop() when removing the disabled property to the submit button)
$("#radioGroupBy").on("change", ":radio[name=group]", function() {
var $radioButtons = $(":radio[name=group]");
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
$("input[name='submitbtn']").prop("disabled", false);
}
});
I figured it out. As Benjamin suggested in comments above, the latter script was executing before the DOM was ready. I solved it by just surrounding the whole script in $(window).load... :
$(window).load(function () {
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
});
http://jsfiddle.net/B9Fub/
<tr class="fis">
Test: <input type="text" name="test" id="test" value="Test">
<tr class="fis">
Empty: <input type="text" name="empty" id="empty">
<input type="button" value="find" id="find">
$('#find').click(function() {
alert('wont work if any other fields are filled other than TEST');
});
$('#test').change(function() {
// needs to fill the form for other functionality
$('#empty').val('empty');
alert('change');
});
So here I have fields that are filled when the first input is 'changed'
But I don't want it to run [change] if they input in the first field and click the 'find' button.
I was wondering if there was a way to do this. From what I found, 'change' happens before the 'find' button if you click on it.
I've tried changing 'change' to 'focus' and give it to the other field so the first field has no event handlers, but that may give me trouble further down the way.
I need the fields to be filled but I don't want them filled if the user clicks the find button.
The mousedown event fires before the change event, so by using that and jQuery's data() method you can set a flag to see if the activeElement is in fact #test when the find button is clicked, and if so don't set the value :
$('#find').on('mousedown', function() {
$('#test').data('flag', document.activeElement.id === 'test');
});
$('#test').on('change', function() {
if ( ! $(this).data('flag') ) $('#empty').val('empty');
});
FIDDLE
Still, not sure what you want. Maybe this will help.
var frm = $('form')[0]; //assuming you have one form on that page
var fnd = $('#find');
fnd.click(function(){
var te = 0, fe = 0;
if(frm.elements[0].value !== '')te = 1;
for(var i=1,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')fe = 1;
}
if(fe === 1){
return false;
}
else{
// do your thing here
return true; // some editors show an error if you don't always return a value
}
});
$('#test').change(function(){
if(fnd.val() !== ''){
return false;
}
else{
// do your thing here
return true;
}
});
I've found the answer. Using e.stopPropagation(); on $('#find') allowed me to stop the .change() from occurring
I have this function:
$(document).ready(function(){
function Fos(buttonSel, inputSel, someValue, cssProperty) {
$(buttonSel).click(function(){
var value = $(inputSel).attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, someValue, this.id)
var css_obj={};
css_obj[cssProperty]=value;
$(this).css(css_obj);
});
});
}
Here are three places where function is written:
Fos('#border_button', '#border-radius', 2, '-webkit-border-radius');
Fos('#background_color_button', '#background-color', 1, 'background-color');
Fos('#opacity_button', '#opacity', 3, 'opacity');
<input type="text" id="border-radius" value="20px">
<div id="border_button">BORDER RADIUS</div>
<input type="text" id="background-color" value="red">
<div id="background_color_button">Background</div>
<input type="text" id="opacity" value=".5">
<div id="opacity_button">Opacity</div>
<div id="2" class="defaultclass editable" style="<?php getStyle('2') ?>">
something
</div>
When you click the DIV with the ID= "border_button", or "background_color_button", or "opacity_button"
it waits for you to click any DIV with class="editable", ...$("div.editable").click(function (e) {... it executes the function with those parameters.
I just need a fix that will only allow ONE function with the parameters to be enabled at one time.
Currently, when you click on all three divs with ID = "border_button", or "background_color_button", or "opacity_button" AND THEN on a div with class="editable", it executes the function with ALL THREE sets of parameters.
This is bad. I can't figure it out.
You can't "disable" a function, but you can set a variable that will force it to exit right away:
var stopMe = true
function myFunction() {
if(stopMe) {
return;
}
...
}
You seem to be binding and rebinding the same functions over and over, which is probably why you have that e.stopEventPropagation in there. Try assigning the events once and then managing the current state (which button is active) and going from there:
var $currentInput = null;
$("#border_button,#background_color_button,#opacity_button").click(function() {
if ($currentInput == null) {
$currentInput = $(this).prev();
}
});
$("div.editable").click(function(e) {
if ($currentInput == null)
return;
$(this).css(GetCssProperties());
showUser($currentInput.val(), /* where does someValue come from? */, this.id)
$currentInput = null;
});
function GetCssProperties() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "border-radius") return {
"-webkit-border-radius": value
}
if ($currentInput.attr("id") == "background-color") return {
"background-color": value
}
if ($currentInput.attr("id") == "opacity") return {
"opacity": value
}
}
working example here: http://jsfiddle.net/HUJ5A/
Run the function for tag with a specific class. And a the end of the function remove this class from the tag.
jQuery(".myclass").click(function(){
/* do something */
jQuery(this).removeClass('myclass');
});
Can't tell everything from your question. But this part $("div.editable").click(function (e) { will bind multiple click events to div.editable each time the user clicks Foo arugments[0] or buttonSel.
This could be a pssible solution:
Have a global variable (or HTML hidden input) say, lastDivClicked, to store the id of the recently clicked div
Update lastDivClicked everytime one of those three divs are clicked upon
Change your function to this:
function Fos(inputSel, someValue, cssProperty) {
var buttonSel = $('#lastDivClicked').val();
$(buttonSel).click(function(){ ... }
}