Disable Inputs on Dropdown Change - javascript

So I'm working on a webform right now and I need to disable all forms of input once one has a specific value. Is there an easy way to handle as soon as that dropdown gets to that value?
Currently I'm doing this:
setInterval('check()', 5000);
function check() {
// Disable all fields if the answer was no.
if ($("#has_contract").val() == 0) {
disable();
}
function disable() {
$("#inputs *").prop('disabled', true);
alert("There is no contract, please get a contract.");
}
has_contract is my element, and #inputs contains all of the inputs I would like to disable if #has_contract's value is 0.**
But this isn't ideal.
Is there a better way to do this rather than constantly checking every X amount of seconds?

Instead of checking for the value every 5 seconds, you can check the value on change.
// collect elements
var $hasContract = $("#has_contract");
var $inputs = $("#inputs input");
// on change, check the input
$hasContract.on('change', checkForm);
// Checks the hasContract input for a value
// of 0. If it does, disable the form.
function checkForm() {
if($hasContract.val() == 0) {
$inputs.attr('disabled', true);
}
}
Also, when you use setTimeout, or setInterval you don't have to use a string. Javascript supports passing functions as variables. See below.
// Do NOT do this
setInterval('check()', 5000);
// Do this instead
setInterval(check, 5000);
// or this
setInterval(function() {
//preform the check...
}, 5000);

I'm not completely certain that I understand your requirements, but would this work for you?
The below assumes that #has_contract is a <select> element:
$("#has_contract").change(function() {
if ($("#has_contract").val() == 0) disable();
});

First off, you should cache the elements as a variable and then run the function against that variable.
var myInputs
$(document).ready(function(){
myInputs = $("#inputs input"); // or '#inputs *' if you're excited about the asterix
});
Second thing, if I'm reading your setup correctly, you're going to pop an alert box every 5 seconds until the user has selected 'yes' to the contract. That will get QUITE annoying and they probably won't want to open a contract with you after that.
Without actually seeing your page, I'd imagine a better solution would be to check for the contract=yes when the click a submit button of some sort on the page.
$('#mySubmitButton').click(function(){
if ($("#has_contract").val() == 0) {
disable();
}
});
But maybe go one step further, what you really want to do is give them access to the form once they agree to the contract. So you should have the form disabled by default (coded into the html that everything is disabled), and attach a function to the 'yes' button that enables the form. Additionally, you can attach a function to the 'no' button that re-disables it, if they had previously clicked 'yes'.
$('#myYesBtn').click(function(){
myInputs.prop('disabled', false);
});
$('#myNoBtn').click(function(){
myInputs.prop('disabled', true);
});

Related

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

Pass a flag from one event to another in Jquery

If I have a Text Input field in a form with id say "input_id". During loading the page I would populate the field with existing data
While submitting the form using a button of id "form_submit", I want to determine if the field has been altered in any way. So that I would take particular action pertaining to the change.
In Jquery:
$("#input_id").on("keyup",function(){
//set a flag to indicate the field is altered
})
$("#form_submit").on("click",function(){
//check flag to see if #input_id is changed
}
So how do I set a flag in one event, and read it in another without using a global variable ?
Thanks in advance
One option would be to use the form data attribute:
$("#input_id").on("keyup",function(){
//set a flag to indicate the field is altered
$(this).closest('form').data('changed',true);
})
$("#form_submit").on("click",function(){
//check flag to see if #input_id is changed
console.log($(this).closest('form').data('changed'));
}
You can use .data() for this purpose,
var submit = $("#form_submit");
$("#input_id").on("keyup",function(){
submit.data("changed",true);
});
submit.on("click",function(){
if($(this).data("changed")){ //do something }
}
So why not just an upper scope flag?
var flag = false;
$("#input_id").on("keyup",function(){
// check stuff ...
flag = true;
});
$("#form_submit").on("click",function(){
if (flag) {
} else {
}
}

How to effectively add additional custom JQuery function to Submit Button on Forms with SilverStripe

I am using SilverStripe 3.0 with the silverstripe-userforms submodule.
This is really difficult to explain so please be patient.
I want to add a custom function (check textarea word count) to a Form, however I am unsure of how best to attach the function as I dont want to hack the core validation js files.
$('button[type="submit"]').entwine({
onclick: function () {
var $this = $('textarea.max-words');
var wordcount = getWords($this);
if (wordcount > maxWords) {
if ($this.next().is("span")) {
$('#maxwords-error').html(function () {
return spanText(wordcount, maxWords);
});
}
else {
$this.after(function () {
return "<span id='maxwords-error' class='required message'>" + spanText(wordcount, maxWords) + "</span>"
});
return false;
}
}
}
})
Silverstripe uses the entwine library so I have tried to do the same.
My problem is this
When run, the user is first prompted to complete the required word count as per the function above.
Once this condition is met, other additional validation be run as per the module (e.g. need to add a valid email address to the email field) form fields.
The user can complete the word count as per custom function, but if another part of the validation fails (e.g. the email field does not contain a valid email) the user can add an email, but then change the word count and submit successfully. Once the function is successful it never seems to run again.
How do I get my custom function to run each time the submit button is pushed, irrelevant of if the word count was correct or incorrect previously.
I think you should also cancel the click event so that it doesn't get propagated. Something like this (simplified):
$('button[type="submit"]').entwine({
onclick: function (evt) {
if(wordCountValidationFailed){
evt.preventDefault();
evt.stopPropagation();
evt.stopImmediatePropagation();
return false;
}
}
});
This ensures that execution of the event pipeline will stop, as soon as your word-count check fails. This should prevent the submission of the form if all form fields – except the word-count – are valid.

Javascript Object Ready?

I have a function that uses AJAX to get a list of items from a php script and can pass a filter. The user can set the filter by selecting from a drop down box on the page.
The problem i'm having is I am calling the function during page load to fill the form with default data and the function is just quitting silently when I try to read the filter text from the drop down box. It works fine after page load, but not during. However the function works fine if I put an alert("test") before it tries to read from the drop down so i'm assuming the drop down just hasnt finished loading properly when the function is called. How can I test to see if its safe to read so I can provide my own default value if it isnt safe?
Code Snippit:
var ProdCat = document.getElementById("prod_cat2");
var Filter = "All Products";
Filter = ProdCat.options[ProdCat.selectedIndex].text;
alert("test");
xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();
So the above code is in a function called onLoad and the alert doesnt trigger at all. But if I comment out the Filter = ProdCat.(etc) line then the alert DOES trigger. Alert ALWAYS triggers even with that line AFTER page load. Looking for a solution to keep the one function both during load and after, thanks!
It sounds like the script is above the markup for the ProdCat select box in your HTML file. If so, the simplest thing is to simply move the script tag containing it down so that it's underneath the markup for the select box. The select box won't exist until its markup is parsed, but it will exists immediately once it is.
How can I test to see if its safe to read so I can provide my own default value if it isnt safe?
If you don't want to relocate the script (or you run into this in other situations where that doesn't make sense), you can test whether you got the element:
if (ProdCat) {
Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
If you like, you can even have it retry:
var ProdCat;
var Filter = "All Products";
function startAjax() {
ProdCat = document.getElementById("prod_cat2");
if (ProdCat) {
Filter = ProdCat.options[ProdCat.selectedIndex].text;
xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();
else {
setTimeout(startAjax, 100); // 1/10th of a second later, try again
}
}
startAjax();
Update: In a comment, you said:
The error is: ProdCat.options[ProdCat.selectedIndex] is undefined
Okay, so you have the element, but there's nothing selected (yet). So the test would be:
if (ProdCat && // We have the select
ProdCat.selectedIndex >= 0 && // and it has a selected value
ProdCat.options[ProdCat.selectedIndex] // (Paranoia) and that option exists
) {
Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
Check if the element could be found. If not, the default filter 'All Products' is used.
var ProdCat = document.getElementById("prod_cat2");
var Filter = "All Products";
if (ProdCat)
{
Filter = ProdCat.options[ProdCat.selectedIndex].text;
}
alert("test");
xr2.open("GET","hs_shop.php?ajaxreq&r=prodlist&p1=" + Filter, true);
xr2.send();

How can I make this username suggestion work in javascript?

I have an application that requires both first name and last name. I need to have the username field automatically fill up as the user types in their first and last names to suggest a username. Right now, it works to a degree. This is the function that executes on a keyup for the name fields.
suggestUsername: function() {
var username = this.$('#user_login_field').val();
var first = this.$('#user_first_name_field').val();
var last = this.$('#user_last_name_field').val();
if(first == '' && last == ''){
this.$('#user_login_field').val('');
} else {
this.$('#user_login_field').val(first+'.'+last);
}
},
This works unless the user adds something to the username manually and then goes back to one of the name fields and enters something else. In the case that that happens, whatever the user added manually disappears. Not sure how to go about fixing it
Add an jQuery focus handler to the #user_login_field that unbinds the keypress events from the first and last name fields. (http://api.jquery.com/focus/)
$('#user_login_field').focus(function (e) {
// Unbind the keyup events
$('#user_first_name_field').unbind('keypress');
$('#user_last_name_field').unbind('keypress');
});
you can add a
$('#user_last_name_field').blur(function(){
//do username suggestion
})

Categories

Resources