How to disable the button if the input has no arrays? - javascript

I have the following in my HTML thing, The input value will be populated by the user selection and store the values in the format of array( 45[45, 6, 33], 67[67,2,5] and so on.. ). Basically the value would be like the following:
<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">
Now i need to disable the submit button or alert some messages like 'Select all values' if the input has no arrays in the {}.
Updated:
var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);
var myArray = new Array();
myArray[0] = window.batch_question_id;
myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
myArray[2] = window.build_id
This bit of above code store the values into the {}. I just want to disable and let the user to select all the fields to process the form. If the values are {}, the button should disabled. and any of the values inside and it should be enabled.
I have tried like the following:
$('.submit_updates').click(function () {
if ($('#question_string') == {}) {
return false;
alert("Select all the Values");
} else {
return true;
}
});
It's not working..
Any help would be appreciated! Thanks

$('.submit_updates').on('click', function (e) {
e.preventDefault();
if ( $.trim($('#question_string').val())=='{}' ) {
alert('no question !');
}else{
this.form.submit();
}
});

You are returning false before alerting the message.
Try this:
$('.submit_updates').on("click", function () {
if ($('#question_string').val() == "{}") { //Adjusted condition
//Alert message
alert("Select all the Values");
//Disable the submit button
$(".submit_updates").prop("disabled", true);
return false;
} else {
return true; //Not really needed
}
});
It is nicer to use on and prop instead of click and attr, as #adeneo suggests.

Try this
$(function(){
$('.submit_updates').on('click', function () {
if ($('#question_string').val() == "{}") {
$(this).prop('disabled', 'disabled');
alert("Select all the Values");
} else {
}
});
});
DEMO

Related

Validate a form only if every input is empty

Well, the question's pretty self-explanatory. I've been looking for a while and haven't found a proper way to do this kind of validation.
All I need to do is to run an error message if all the inputs are empty. If one of them is filled, then I don't need to stop the form from submitting.
I thought something like:
function checkForm() {
$('input').each(function(){
if( $(this).val() == "" ){
return false;
}
});
});
But this will stop my form if there's, at least, one input without data.
Any ideas? Thanks in advance.
Reverse your logic. I.e. return true if any input has a value, otherwise return false:
function checkForm() {
$('input').each(function() {
if ($(this).val() !== '') {
return true;
}
});
return false;
};
Reverse your logic since you want to check if the value is non-empty for one input field.
Also you probably want to return from your actual function and not from the callback which has no effect.
function checkForm() {
let bool = false;
$('input').each(function(){
if( $(this).val() !== '' ){
bool = true;
}
});
console.log(bool);
return bool;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<button onclick="checkForm()">check</button>

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

JQuery Validation for Two Password Fields

Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
    $(".error").show(500);
}else{
 $(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.

how do i put the following in a for loop

I would like to put the following in a for loop but i am having difficulties. Any help would be appreciated
$("input:submit").click(function(){
if (!$("input[name=attendance1]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance2]").is(":checked")) {
alert('Please select preference');
return false;
}
else if (!$("input[name=attendance3]").is(":checked")) {
alert('Please select preference');
return false;
}
});
});
I have tried:
for($i=1; $i<=3; $i++)
{
$("input:submit").click(function(){
if (!$("#food" + $i).is(":checked")) {
alert('Please select preference');
return false;
}
});
});
First fix:
alert('Please select preference);
with
alert('Please select preference');
Then if you want to loop:
for (var i = 0; i < 3; i++) {
if (!$("input[name=attendance" + i + "]").is(":checked")) {
alert('Please select preference');
return false;
}
}
Or better yet use jQuery's startsWith selector:
if (!$('input[name^="attendance"]').is(":checked")) {
alert('Please select preference');
return false;
}
Example
You're missing a closing single quotation mark on all 3 alert statements.
I generally use a class name on my DOM elements when I want to do something like this. That makes it easier to iterate through the elements using .each(). I was not aware of the startsWith selector mentioned above, but it does look a bit cleaner than my method.
<!-- DO STUFF -->
<input name="attendance1" class="my-unique-class-name" />
<input name="attendance2" class="my-unique-class-name" />
<input name="attendance3" class="my-unique-class-name" />
<!-- DO STUFF -->
<script type="text/javascript">
$("input:submit").click(function(){
var valid = true;
$("input.my-unique-class-name").each(function (el) {
if ( ! $(el).is(":checked") ) {
valid = false;
}
});
if ( ! valid ) {
alert('Please select preference');
return false;
}
});
</script>
Here's my take on it. it has the advantage of you listing down in an array what names you want checked, regardless what names they are
//jQuery '.on()' for versions 1.7+
$("input:submit").on('click', function() {
//assume valid unless found otherwise
var valid = true;
//add the input names you want to verify
var nameList = [
'attendance1',
'attendance2',
'attendance3'
];
//loop through names
for (var i = 0; i < nameList.length; i++) {
var checked = $('input[name="'+nameList[i]+'"]').is(':checked');
if (!checked) {
alert('Please select a preference');
//mark false when something wrong found
valid = false;
}
}
//check if validity persisted
if(valid){
//do something
}
//prevent default actions
return false;
});​

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories