I have an issue, with ajax request. When button enter is clecked it is doubles ajax request. I spent 4 hours dealing with it and no effect at all. Can someone help me with it. I have created consol.log here. For better understanding of my bad code. Thank you in advanced!
let formSubmitHandler = (data) => {
console.log(data)
// $.ajax({ url: 'index.php',
}
let handleInputEdit = (data) => {
let onFocusHandler = (element) => {
element.keypress(function( event ) {
if ( event.which == 13) {
let inputData = element.val();
let name = element.attr('name');
return onHandlerFormData(name, inputData);
}
})
}
let onHandlerFormData = (name, data) => {
let str = `${name}=${data}`;
$('#data').html(str)
return formSubmitHandler(str);
}
let onEditHandler = () => {
let checkboxes = document.querySelectorAll('input[type=checkbox]');
for (let i = 0; i < checkboxes.length; i++) {
const element = checkboxes[i];
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", true);
if (element.checked) {
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", false)
.focus(function(){
onFocusHandler($(this));
})
}
}
};
onEditHandler();
$("input[type=checkbox]").on("click", onEditHandler);
}
handleInputEdit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainForm">
<label for="companyName">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="companyName"
type="text"
class="form-control"
aria-label="..."
name="companyName"
>
</div>
<label for="edrpou">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="edrpou"
type="text"
class="form-control"
aria-label="..."
name="edrpou"
>
</div>
</form>
You are calling onFocusHandler multiple times. You binding the onFocusHandler multiple times each time the checkbox is clicked. Moving the onFocusHandler from the definition of onEditHandler will solve this issue. Try out the following code,
The onEditHandler will change as follows,
let onEditHandler = () => {
let checkboxes = document.querySelectorAll('input[type=checkbox]');
for (let i = 0; i < checkboxes.length; i++) {
const element = checkboxes[i];
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", true);
if (element.checked) {
let getNaighborInput = $(element).parent().next();
getNaighborInput.attr("disabled", false)
}
}
};
And bind the onFocusHandler function with the checkboxes only once as follows,
$('input[type=checkbox]').each(function () {
onFocusHandler($(this).parent().next());
});
I have re-written the javascript to handle enabling/disabling the textboxes, and also to handle keyup event for the ENTER press.
I think the code is more readable this way, plus: it works as expected.
// disable all textboxes by default
$('input[type=text]').attr('disabled','disabled');
//only enable the textbox next to the checkbox if it was checked
$(document).on('click','input[type=checkbox]',function(){
if ($(this).is(':checked')) {
$(this).parent().siblings('input[type=text]')
.removeAttr('disabled');
} else {
$(this).parent().siblings('input[type=text]')
.attr('disabled','disabled');
}
});
//whenever the ENTER key is pressed within an enabled textbox, handle it
$(document).on('keyup','input[type=text]',function(e) {
if(e.which == 13) {
console.log( $(this).attr('id') + '=' + $(this).val() );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainForm">
<label for="companyName">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="companyName"
type="text"
class="form-control"
aria-label="..."
name="companyName"
>
</div>
<label for="edrpou">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="edrpou"
type="text"
class="form-control"
aria-label="..."
name="edrpou"
>
</div>
</form>
Like Ahmad... I also re-written your way too complex code.
It made my brain bleed.
And it does a so simple task in the end!
About changes on HTML, I only added the disabled attribute straith in the markup.
Have a look:
$("#mainForm input[type='checkbox']").on("click",function(){
var text_input = $(this).parent().next("input");
var text_input_dasbled = text_input.prop("disabled");
text_input.attr("disabled", !text_input_dasbled); // Toggle disabled
});
$("#mainForm input[type='text']").on("keyup",function(e){
if(e.which==13){
var data = {[$(this).attr("name")]:$(this).val()};
console.log(data)
// $.ajax({ ... });
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<form id="mainForm">
<label for="companyName">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="companyName"
type="text"
class="form-control"
aria-label="..."
name="companyName"
disabled>
</div>
<label for="edrpou">Label 2</label>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<input
id="edrpou"
type="text"
class="form-control"
aria-label="..."
name="edrpou"
disabled>
</div>
</form>
Related
I want to remove the disabled attribute from the button when each field is filled out.
My code works when a single input is filled.
What am i doing wrong here?
Here are the HTML and JS
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
if (e.value !== '') {
disabled = false
} else {
disabled = true
return false
}
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Continue</button>
It does not work because you want to have all inputs affect the state of a button, yet you only check one variable for adding/removing disabled property.
Here is a working code snippet with an example where i created an array of properties, one for each input, that i can refer to in every fired key up event
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
const disabled = Array(input.length).fill(true);
input.forEach(function (e, index) {
e.addEventListener('input', function () {
disabled[index] = e.value === ''; // simplified if/else statement of yours
if(disabled.some(Boolean)) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Prosegui</button>
Additionaly stoping the function execution when assigning disabled = true in the first else statement is also a wrong approach, as you most likely want to not only assign the disable value, but also the disabled property of the button.
EDIT: as mentioned in the comment by CID it is reasonable to change the event listener to input so we can handle the copying and pasting events as well
You are adding a keyup event for each input field.
that event only checks the current input field if it is empty or not.
it does not check the 3 input fields itself
this should do the trick:
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
const emptyFields = Array.from(input).filter( input => input.value === "");
disabled = emptyFields.length > 0;
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
You are enabling the submit button on keyup event of any 3 inputs. So it gets enabled on any 3 inputs.
Remove the return on disabled flow to disable button after clearing.
checkInput()
function checkInput() {
let input = document.querySelectorAll('.form-control')
const button = document.querySelector('.submit-btn')
input.forEach(function (e) {
let disabled = true;
e.addEventListener('keyup', function () {
if (e.value !== '') {
disabled = false
} else {
disabled = true
// return false <-- this makes function exit before your disable button
}
if(disabled) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
})
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Continue</button>
Another solution is to check if all inputs are filled out on every change in any input.
addHandlers();
// Return true if all fields are not empty
function areAllFieldsFilledOut() {
let inputs = document.querySelectorAll('.form-control');
let result = true;
inputs.forEach(e => {
if (e.value === "")
result = false;
});
return result;
}
// Add keyup event handlers to all input fields
function addHandlers() {
let inputs = document.querySelectorAll('.form-control');
const button = document.querySelector('.submit-btn');
inputs.forEach(e => {
// On each change in any input, check if all inputs are
// not empty, and if true, enable the button
e.addEventListener('keyup', e => {
let result = areAllFieldsFilledOut();
if (result) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', 'disabled');
}
});
});
}
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control" type="text" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="lastName">lastName*</label>
<input class="form-control" type="text" id="lastName" placeholder="lastName">
</div>
<div class="form-group">
<label for="fiscalCode">fiscalCode*</label>
<input class="form-control" type="text" id="fiscalCode" placeholder="fiscalCode">
</div>
<button type="submit" disabled="disabled" class="submit-btn">Prosegui</button>
Here is my answer:
function checkInput() {
document.querySelectorAll('input').forEach(input => {
input.addEventListener('keyup', function () {
let emptyFieldsCount = Array.from(input).filter(input => input.value == "").length;
if (emptyFieldsCount > 0) {
button.setAttribute('disabled', 'disabled')
} else {
button.removeAttribute('disabled')
}
})
});
}
Im having trouble getting values from the checked radio:
<form id="addform" /*action="catch.php" method="POST"*/>
<div class="form-group input-container">
<label class="col-sm-7"> *Href looks like "/vacacy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="0" type="radio" required>
<label class="col-sm-7"> *Href looks like "https://www.test.com/vacancy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="1" type="radio" required>
</div>
</form>
This is the JavaScript code:
$( "#check" ).click(function()
{
var $inputs = $('#addform :input');
var values = {};
$inputs.each(function()
{
if (this.name === "vacancy_full_URL")
{
if (/* check if radiobutton is checked */)
{
values[this.name] = $(this).val();
}
}
else
{
values[this.name] = $(this).val();
}
});
});
I'm having trouble finding the right functions to check this with. My earlier attempt if (this.checked() === true) did not work. Can you please help me?
Use is(":checked") to find if a radio button is checked. Also there are few mistakes in html form like a you have make the form self closing. Secondly there was no item with id check
$("#check").click(function(e) {
e.preventDefault()
var $inputs = $('#addform :input');
var values = {};
$inputs.each(function() {
if (this.name === "vacancy_full_URL" && $(this).is(":checked")) {
values[this.name] = $(this).val();
} else {
values[this.name] = $(this).val();
}
});
console.log(values)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addform" action="catch.php" method="POST">
<div class="form-group input-container">
<label class="col-sm-7"> *Href looks like "/vacacy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="0" type="radio" required>
<label class="col-sm-7"> *Href looks like "https://www.test.com/vacancy/12": </label>
<input class="col-sm-3" name="vacancy_full_URL" value="1" type="radio" required>
</div>
<button type='submit' id='check'>Click</button>
</form>
You can handle click event on button and check radion click name with :checked
$(document).ready(function(){
$("#check").click(function(){
var radioValue = $("input[name='vacancy_full_URL']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
Please try this.
$(document).ready(function () {
$("#check").click(function () {
var values = {};
var other_data = $('input[type=radio]', $('#addform'));;
$.each(other_data, function (key, input) {
if (input.checked) {
values[input.name + "_checked"] = input.value;
} else {
values[input.name+ "_unchecked"] = input.value;
}
});
});
})
I am having 6 bootstrap cards where the details of the card are id, image, content.on clicking the card I am getting the details of the card into the local storage and from that, I am extracting the ids into another array named styleIds I want these styleIds values to sent as value to the input field as onload of body
My js code:
var styles = []
var styleIds = []
function getStyle(id) {
if (styles.length > 0) {
var data = { id: id, image: $("#img_"+id).attr('src'),content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
var index = styles.indexOf(x)
if (index == -1) {
styles.push(x)
}
else {
styles.splice(index, 1)
}
}
else {
var data = { id: id, image: $("#img_"+id).attr('src'),content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
styles.push(x)
}
localStorage.setItem("styles", JSON.stringify(styles))
styleIds = styles.map(element => JSON.parse(element).id);
console.log(styleIds)
assample();
}
function assample() {
$("#style").val(styleIds);
console.log(styleIds)
}
function initStyles() {
var storedNames = JSON.parse(localStorage.getItem("styles") || '[]');
styleIds = storedNames.map(element => JSON.parse(element).id);
}
My form code is:
<body onload = "sample();initGoals();issample();assample();initStyles();">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<input type="text" name="room" id="name" value=" ">
</div>
<div class="form-group" >
<input type="text" name="goal" id="goal" value=" ">
</div>
<div class="form-group" >
<input type="text" name="style" id="style" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">
</form>
The cards are on one page and the form is the another web page so in the styles page the styleIds array is getting the ids butwhen I navigate to the form page the values are getting as a value for the field in the form what is the mistake I did?
Make sure you're calling the functions in the correct order. Also, I would suggest renaming your function names so that you don't get confused.
You can change your onload to just call one function and later care about the order.
<body onload = "doSomething()">
and in the script:
function doSomething() {
sample();
initGoals();
issample();
initStyles();
assample();
}
I made a JQuery function to check for empty required fields inside a closed custom dropdown.
If a required field is empty inside one of the dropdown and if the dropdown is currently closed I want the dropdown to open and if there are no empty values in the required fields I want the dropdown to close.
The problem is that the required fields aren't accessible if the dropdowns are closed and I tried to fix that problem with this function.
For some reason, it only checks for these input fields if the form is submitted at least once and the required fields are opened at least once.
find(':input[required]') doesn't give any output if the dropdown isn't opened at least once, once u open and close the dropdown the function works.
This is the function:
function dropdown_required() {
var required = 0;
$('#visible_fields').find(':input[required]').each(function () {
if (!this.value) {
for (var i = 1; i < 15; i++) {
$('.form_' + i).find(':input[required]').each(function () {
$(this).prop('required', false);
});
}
required++;
}
});
if (required == 0) {
for (var i = 1; i < 15; i++) {
var empty = 0;
$('.form_' + i).find(':input[required]').each(function ()
{
if(!this.value) {
empty++;
}
});
if (empty !== 0) {
if ($(".arrow_" + i).hasClass("rotate_2")) {
$(".arrow_" + i).addClass("rotate_1").removeClass("rotate_2");
$(".form_" + i).fadeToggle();
}
} else if ($(".arrow_" + i).hasClass("rotate_1")) {
$(".arrow_" + i).addClass("rotate_2").removeClass("rotate_1");
$(".form_" + i).fadeToggle();
}
}
}
}
This is the html:
<form method="POST" autocomplete="off" enctype="multipart/form-data" target="_self"
action="/contacten/leveranciers/iframe{{ ($leverancier == null ? '' : '/' . $leverancier->cot_id) }}">
{{ csrf_field() }}
<div id="visible_fields">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="organisatie">Organisatie</label>
<input type="text" name="organisatie" id="organisatie" blocked=",;()/" hk="a"
value="{{ ($leverancier == null ? old('organisatie') : $leverancier->cot_organisatie) }}"
class="form-control inputblocked">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" filter="a-zA-Z0-9" maxlength="6"
value="{{ ($leverancier == null ? old('postcode') : $leverancier->cot_postcode) }}"
class="form-control inputfilter filter_postcode">
</div>
</div>
</div>
//all visible input fields outside of the dropdowns
</div>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="bkr">BKR</label>
<select name="bkr" class="form-control" required>
<option selected hidden></option>
<option value="10">BKR toetsing open</option>
<option value="11">BKR toetsing accoord</option>
<option value="12">Vrijgesteld van BKR toetsing</option>
</select>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="bkr_bestand">BKR bestand</label>
<input type="file" name="bkr_bestand" id="bkr_bestand"
data-default-file=""
class="form-control dropify">
<input type="hidden" name="verwijder_foto" class="verwijder_foto" value="0">
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="hidden" id="input_iframe" name="input_iframe" value="">
<button type="submit" onclick="dropdown_required()"
class="btn btn-primary">Toevoegen </button>
</div>
</form>
</div>
</body>
</html>
Your function checks if your arrow element has the class rotate_2. The code you pasted has neither rotate_1 or rotate_2 and no else block, so the toggle never executes.
Problem demonstration:
// This group has empty mandatory elements
var empty = 1;
$('#validate').click(function() {
if (empty !== 0) {
console.log("I have empty elements!");
// From your comments, this might be backwards
if ($(".arrow_1").hasClass("rotate_2")) {
console.log("I'm going to show them");
$(".arrow_1").addClass("rotate_1").removeClass("rotate_2");
$(".form_1").fadeToggle();
}
// This is missing in the code
else {
console.log("I wasn't invited to the party");
}
// -------
} else if ($(".arrow_1").hasClass("rotate_1")) {
console.log("I'm out, I don't have empty elements...");
$(".arrow_1").addClass("rotate_2").removeClass("rotate_1");
$(".form_1").fadeToggle();
}
});
$('#simulate').click(function() {
// Simulates manually opening and closing
// In short, add rotate_2 class as if it's been toggled
$('.arrow_1').addClass('rotate_2');
console.log("Toggled manually");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div>Some form elements</div>
</div>
<button id="validate">Validate</button>
<button id="simulate">Simulate</button>
Disabling jquery submit button until all the form inputs is filled.
Am working with Jquery and I have been trying to implement disabling form submission button until the whole form inputs are filled. i have tried most solution found here but it does not solve the issue. Thanks
$('.postbtn_video').click(function() {
var element = $(this);
var ID = element.attr('id');
var msg = $('#status').val();
var title = $('#title').val();
var video = $('#video').val();
var stat = $('#stat').val();
if (title == "") {
alert('Please Enter video Post Title?');
} else if (msg == "") {
alert('Please Enter Video Post Description');
} else if (video == "") {
alert('Enter Youtube Video Link');
} else if (stat == "") {
alert('Select Status');
} else {
var postData = "post=" + msg + "&title=" + title + "&video=" + video + "&stat=" + stat;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "posts.php",
data: postData,
cache: false,
success: function(html) {
$("ul#updatepost").prepend(html);
$("ul#updatepost li:first").slideDown("slow");
$('#status').val('');
$('#loader').hide();
}
});
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?">
</textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
</form>
Firstly apply disabled="disabled" to the button:
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
Secondly, you need a function which will check each field is empty or not!
Check below code:
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if(!empty){ // this will only check next inputs if empty is false, but once its set to true no further check will be made
if ($(this).val() == '') {
empty = true;
}
}
});
if (empty) {
$('.postbtn_video').attr('disabled', 'disabled');
} else {
$('.postbtn_video').removeAttr('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?"></textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
</form>
Maybe this will help. you can manipulated the Form Disabled attribute:
var checkboxes = document.getElementsByTagName('input');
//check all check all input elements to see if they are check-boxes
for (var i = 0; i < checkboxes.length; i++) {
//If the input is a check-box run script else skip over
if (checkboxes[i].type == 'checkbox') {
//If it is a check-box ensure the box is unchecked
checkboxes[i].checked = false;
}
}
$(document).ready(function()
{
//define Element by ID and create variable
var $checked = $('#field_human');
//define default state for attribute before handler function trigger
$("#submit").attr("disabled", !$checked.checked)
//On element handler trigger define function to execute each time handler is triggered
$checked.click(function()
{
//State to define instance on method
if ($checked.prop('checked'))
{
//return true
//remove element attribute state 'disabled'
$('#submit').removeAttr('disabled');
}
if($('#contactForm input').val() != '')
{
$('#submit').removeAttr('disabled');
}
else {
//return false
//set element attribute state 'disabled'
$("#submit").attr("disabled", !$checked.checked);
}
//return to ready-state to wait for handler to trigger again
return;
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<form class="form-horizontal" role="form" method="post" action="" id="contactForm" name="contactForm">
<div class="form-group">
<label for="inputblk" class="col-sm-3 control-label">Input Block</label>
<div class="col-sm-9">
<input name="inputblk" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-3 control-label">Are You <strong><u>Human</u>?</strong></label>
<div class="col-sm-9">
<input id="field_human" class="field_human" type="checkbox" name="human" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button id="submit" name="submit" type="submit" class="btn btn-dark btn-block btn-lg">Send</button>
</div>
</div>
</form>
1st:
inputs that you think are required, make it required! like below:
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link" required >
2nd:
Make your selection based on this attribute and check if values of these inputs are not empty. Disable the submit button if so.
3rd:
Make event listener to all inputs that have required attribute to listen user inputs.
something like this:
var l = $("[required='']");
function enableSubmit(l) {
if (l.length == 0) {
$("[name=post]").removeAttr('disabled');
} else {
for (var m = 0; m < l.length; m++) {
if (l[m].value.length == 0) {
$("[name=post]").attr("disabled", "disabled");
return;
}
}
$("[name=post]").removeAttr('disabled');
}
}
for (var m = 0; m < l.length; m++) {
l[m].addEventListener('input', function () {
enableSubmit(l);
});
}
First of all you need to add a disabled property to you input button by default like:
<input disabled name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
then in your jquery you need fire up a validate function that will check for all the inputs and if they are not empty you can simply remove the disabled property from your input button like:
$(document).on('keyup', "input:not([type='submit']", function () {
//set it to true by default
var valid = true;
//getting all the inputs except input submit
var inputTextboxes = $("input:not([type='submit'])");
inputTextboxes.each(function(e) {
//it enters this only if the valid is true for any one value, if valid is set to false at any point it won't check it for next inputs - works for first time
if (valid != false){
if ($(this).val()) {
valid = true;
}else{
valid = false;
}
}
else{
break; //breaks the loop
}
});
if (valid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Hope this helps