After clicking on Add Input and adding an input, clicking on the added button doesn't call the required_valid() function in $('.submit').submit(function () {.... Why is this?
DEMO: http://jsfiddle.net/Jvw6N/
Add Input
<div class="get_input"></div>
$('.add_input').live('click', function(e){
e.preventDefault();
$('.get_input').append('<form class="submit"><input name="test" class="required"> <br /> <button>Click Me</button></form>')
})
function required_valid() {
var result = true;
$('.required').each(function () {
if (!$(this).val()) {
$(this).css("background", "#ffc4c4");
result = false;
}
$(this).keyup(function () {
$(this).css("background", "#FFFFEC");
})
});
return result;
}
$('.submit').submit(function () {
var passed = true;
//passed = required_selectbox() && passed;
passed = required_valid() && passed;
if (!passed) {
$('#loadingDiv, #overlay').hide();
return false;
}
});
You need to set up your "submit" handlers with ".live()" (or ".delegate()" or the new ".on()") just like your "addInput" button:
$('body').delegate('.submit', 'submit', function() {
// your submit code here
});
You're adding those forms dynamically, so your handler isn't actually bound to any of them.
Alternatively, you could bind the handler when you add the form.
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'})
}
}
});
We have a submit binding in knockout, however we can use it only on whole form, so in a case of multiple submit buttons, they all trigger same binding. I'd like differ action for each one, but idk how to differ which one has been clicked, eg.:
HTML:
<form data-bind="submit: save">
<input type=submit name=save value=Save>
<input type=submit name=saveAndClose value="Save & close">
</form>
VM:
var ViewModel = function () {
this.save = function (form) {
var clicked = 'how to find out?';
if (clicked === 'save') {
// save
} else if (clicked === 'saveAndClose') {
// save
// close
}
};
};
Yea, I can use click binding on each submit, but then there's no form element available, yea - I can obtain it by different way, but maybe you know better solution.
Do you?
Well, what you can do is to use a click binding on each input and pass a $element variable as a parameter. As such:
<form>
<input type=submit name=save data-bind="click: save.bind(null, $element)" value=Save>
<input type=submit name=saveAndClose data-bind="click: save.bind(null, $element)" value="Save & close">
</form>
bind in javascript creates a new function with a specified this (null) and parameter ($element) in this case. Therefore, it is easy to obtain a form element, and determine which input was clicked:
var ViewModel = function () {
this.save = function (el) {
var clicked = el.getAttribute('name');
var form = el.parentElement;
console.log(clicked, form)
if (clicked === 'save') {
// save
} else if (clicked === 'saveAndClose') {
// save
// close
}
};
};
Working fiddle
Note however, that this method is markup dependent, if the inputs are not direct children of the form element, you may need to find another method to get the form element itself instead of parentElement
Overload submit binding to allow use it on any element.
JSFiddle: Knockout submit binding applicable onto any button (uses jQuery)
Binding overload:
var overridden = ko.bindingHandlers.submit.init;
var $clickedButton;
ko.bindingHandlers.submit.init = function (element, valueAccessor) {
var $form = $(element);
if ($form.prop('tagName') !== 'FORM') {
var $button = $form;
$form = $form.closest('form');
if ($form.length === 0) {
throw new Error('Submit binding can be used only in forms');
}
$button.on('click', function () {
$clickedButton = $button;
});
var formHandler = function () {
return function () {
if ($clickedButton === $button) {
return valueAccessor().apply(this, arguments);
}
return false;
};
};
overridden.apply(this, [$form[0], formHandler].concat([].splice.call(arguments, 2)));
} else {
overridden.apply(this, arguments);
}
};
ViewModel:
var ViewModel = {
submitA: function () {
alert('A');
},
submitB: function () {
alert('B');
}
};
ko.applyBindings(ViewModel);
HTML:
<form method=post>
<input type=submit data-bind="submit: submitA" value=A>
<input type=submit data-bind="submit: submitB" value=B>
</form>
i have a script which check when two textfields are not empty it does automatic submission. it picks the variables from the localstorage and places them in the textfields.
if (localEmail != null && localPwd != null) {
$('#form1').submit();
}
and i also i have a script which disables the submit button when all textfields are not filled.
$(document).ready(function (){
var $input = $('#form1 input:text'),
$register = $('#button_id');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.button('disable') : $register.button('enable');
});
});
now my problem is when the page loads for the second and subsequent times and there are variables from the localstorage in the textfields, the submit button still remains disabled and the automatic submission fails. Now i want the button to remain active when there are variable in it so the automatic submission can be done
In document ready do an additional check for input values and disable the button
$(document).ready(function () {
var $input = $('#form1 input:text'),
$register = $('#button_id');
$input.each(function () {
if (!$(this).val()) {
$register.attr('disabled', true);
return false;
}
});
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
$(document).ready(function () {
var $input = $('#form1 input:text'),
$register = $('#button_id');
$input.each(function () {
if (!$(this).val()) {
$register.attr('disabled', true);
return false;
}
});
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form1">
<input type="text" />
<input type="text" />
<button id="button_id">button</button>
</form>
The reason why you are not achieving the desired behavior is because you are only updating the button's disabled property when a change event is fired from the input element(s), which are not fired by default upon page load.
The solution is to therefore move the function involving updating the button's status into a separate one, which we will call upon runtime (e.g. DOM ready) and then again when the change event is fired on element(s) of interest:
var updateButton = function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.button('disable') : $register.button('enable');
};
// Update button status on DOM ready
updateButton();
// Update button status on keyup
$input.keyup(updateButton);
On a side note, please use .prop() when dealing with binary attributes:
$register.prop('disabled', true);
this should work
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
under document ready function.
$(document).ready(function (){
var $input = $('#form1 input:text');
$register = $('#button_id');
$register.prop('disabled', true);
//$register.attr('disabled', true);
$('#button_id').on('click',function(){alert('hi');});
function checkInputs(){
$input.each(function(e) {
if (!$(this).val().length < 1) {
trigger = true;
} else
{trigger = false;}
});
trigger ? $register.prop('disabled',false) : $register.prop('disabled',true);
}
checkInputs();
$('#form1 input:text').on('keyup',function(){checkInputs();});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<input/>
<input />
<button type="button" id="button_id" >Submit</button>
</form>
I have a javascript function (to Save the form values) already defined globally in a common js file and now I need to override that with some other functionality based on some condition. Is there any way I can attach a javascript function to the a href onclick dynamically? I tried this way but it is not working. Can anyone please help me?
Parent html:
<a href="#" onclick="Save();" id="SaveLink"/>
Common.js:
function Save()
{
//do something
}
My child html calls ValidateForm function (available in Common.js) to validate the form
and if it is not valid then stop calling the global Save() function.
function ValidateForm()
{
var responseValid = false; //false for now
if (!responseValid)
{
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
}
else
{
$("#SaveLink").on("click", "Save();"); //call the global Save function
}
}
Updated Code:
function ValidateForm()
{
var responseValid = false; //false for now
if (!responseValid)
{
//$("#SaveLink").prop("onclick", null);
$("#SaveLink")[0].onclick = null;
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
}
else
{
//call the global Save function
//$("#SaveLink").prop("onclick", null);
$("#SaveLink")[0].onclick = null;
$("#SaveLink").on("click", function (e) {
Save();
e.preventDefault();
});
}
}
<a href="#" id="SaveLink" onclick="$.Save(this.id);"/>
JQuery Code:
$.Save=function(id)
{
//by using id you can apply your conditions
}
You need to remove onclick event
function ValidateForm() {
var responseValid = false; //false for now
if (!responseValid) {
//Remove onclick attribute
$("#SaveLink").removeAttr('onclick');
//OR
$("#SaveLink").prop("onclick", null);
$("#SaveLink").on("click", function (e) {
alert("This response is not valid");
return false;
});
} else {
//call the global Save function
$("#SaveLink").on('click', Save);
}
}
You should pass function handler, not String:
$("#SaveLink").on("click", Save);
EDIT:
To prevent onclick in page you should remove it on DOM ready event. For example:
$( function() {
$( '#SaveLink' )[ 0 ].onclick = null;
});
function ValidateForm()
{
var isSave= true;
//do your form validation
if(validation fail) //if validation fail set isSave is false
isSave=false;
return isSave;
}
function save()
{
if(ValidateForm()) //it will only execute validation is not fail
{
// do your code
}
}
OnClick just call save function only
I want to use some letters ( keys ) as shortcut for some actions in javascript. I want to check whether the cursor is focused on any textfield, form input, etc. so that the shortcut action will be canceled when user is typing something in a form or textfield.
For example, i want an alert() to be executed when user presses 'A'. But if the user is typing some text in a textarea like 'A website' then he will be pressing 'A', this time alert() should not be executed.
$(document).keydown( function( e ) {
if( e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA" ) return;
if( e.target.isContentEditable ) return;
// Do stuff
}
window.onkeydown = function(e){
if ( e.target.nodeName == 'INPUT' ) return;
handle_shortcut();
};
jQuery
$(window).bind('keydown',function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
});
or pure js
window.onkeydown = function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
};
What you can do in addition to this is define an array of non-alert element types, so input, textarea etc and then check none of those elements are currently the target.
Demo: http://jsfiddle.net/7F3JH/
You can bind and unbind the shortcut events depending on which element currently has focus on your page.
JavaScript
window.onload = initWindow();
function initWindow () {
attachShortcutHandler();
var inputs = document.getElementsByTagName('input');
for (var i = 0, max = inputs.length; i < max; i++) {
inputs[i].onfocus = removeShortcutHandler;
intputs[i].onblur = attachShortcutHandler;
}
}
function removeShortcutHandler () {
window.onkeypress = null;
}
function attachShortcutHandler() {
window.onkeypress = function () {
//your code here
}
}
jQuery
$(function () {
initShortcutHandler();
$('input, [any other element you want]')
.on('focus', function () {
$('body').off('keypress');
})
.on('blur', function () {
initShortcutHandler();
});
});
function initShortcutHandler() {
$('body').on('keypress', function () {
//do your stuff
});
}
jQuery mouseover()
$('element').mouseover(function() {
alert('over');
});
you need to make a flag as global. and set it false when any textbox has focus.
var flag = true;
$('input:type="text").focus(function(txt) {
flag= false; });
if(flag) //shortcut keys works...
Better use the focusOut method defined in JQuery. As per my understanding you can do something like this
$("input").focusout(function() {
if($(this).val() == "A"{
alert("your message");
return false;
}else{
//do other processing here.
}
});
Hope this helps :)