I copied this code from my previous website, which was running perfectly fine. However, even when I copied everything over, it doesn't work for some reason.
I've looked through the code and never touched anything, but also fiddled around with a few options I could have thought of. Nothing has worked so far.
https://jsfiddle.net/Lpbmg0z6/
HTML:
<section class="contact__section" id="contact">
<h2 class="vh">Contact Me</h2>
<div class="innerContent">
<div class="contact__form clear all">
<fieldset id="contact_form">
<div class="contactForm__full contactForm__input">
<label for="name" class="all">name</label>
<input type="text" name="name" id="name" />
</div>
<div class="contactForm__full contactForm__input">
<label for="email" class="all">email</label>
<input type="text" name="email" id="email" />
</div>
<div class="contactForm__full contactForm__input">
<label for="message" class="all">message</label>
<textarea name="message" id="message"></textarea>
</div>
<div class="contactForm__full">
<button class="submit_btn all" id="submit_btn" aria-label="Submit message">submit</button>
</div>
<div id="result" class="contactForm__results"></div>
</fieldset>
</div>
</div>
</section>
JS:
$("input").focus(function () {
$(this).parent().find("label").removeClass("labelBlur").addClass("labelFocus");
});
$("input").focusout(function () {
if ($(this).val().length == 0) {
$(this).parent().find("label").addClass("labelBlur").removeClass("labelFocus");
}
});
var inputs = $("input").length;
for (var i = 0; i < inputs; i++) {
$input = $("input:eq(" + i + ")");
if (($input.attr("type") != "checkbox") && ($input.attr("type") != "submit")) {
if ($input.val().length != 0) {
$input.parent().find("label").addClass("labelFocus");
} else {
$input.parent().find("label").addClass("labelBlur");
}
}
}
$("textarea").focus(function () {
$(this).parent().find("label").removeClass("labelBlur").addClass("labelFocus--textarea");
});
$("textarea").focusout(function () {
if ($(this).val().length == 0) {
$(this).parent().find("label").addClass("labelBlur").removeClass("labelFocus--textarea");
}
});
var textareas = $("textarea").length;
for (var i = 0; i < textareas; i++) {
$textarea = $("textarea:eq(" + i + ")");
if (($textarea.attr("type") != "checkbox") && ($textarea.attr("type") != "submit")) {
if ($textarea.val().length != 0) {
$textarea.parent().find("label").addClass("labelFocus--textarea");
} else {
$textarea.parent().find("label").addClass("labelBlur");
}
}
}
All it's supposed to be doing is when you click/focus on one of the inputs, it adds a class, and when you unfocus, it removes that class and adds back the default class.
In your JSFiddle, you've forgotten to include jQuery. Once jQuery is added the code works fine; do you think you've done the same on your actual site?
To add jQuery via a CDN visit https://code.jquery.com/ and pick one of the script tags on offer, e.g.
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
Related
I am trying to make form. When we send information with errors, then should be color red where we entered wrong data and color green where we entered the correct data.
My .js file:
function checkForm()
{
var error=false;
var contactName = document.getElementById("contactName");
var contactLastName = document.getElementById("contactLastName");
var contactEmail = document.getElementById("contactEmail");
var contactInfo = document.getElementById("contactInfo");
if (contactName.value == "")
{
document.getElementById('errorName').className='alert alertdanger';
error=true;
}
if (contactLastName.value == "")
{
document.getElementById('errorLastName').className='alert alertdanger';
error=true;
}
if(contactInfo.value == "")
{
document.getElementById('errorInfo').className='alert alertdanger';
error = true;
}
else
{
var info = contactInfo.value;
if(info.length >= 250)
{
document.getElementById('errorInfoLength').className='alert alertdanger';
error=true;
}
}
if(contactEmail.value == "")
{
document.getElementById('errorMail').className='alert alertdanger';
error=true;
}
else
{
var email = contactEmail.value;
var regex = /^[a-zA-Z0-9._-]+#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
if(regex.test(email)==false)
{
document.getElementById('errorMailCorrect').innerHTML='Bad format!';
document.getElementById('errorMailCorrect').className='alert alertdanger';
error=true;
}
}
if (!error)
return true;
else
{
return false;
}
}
Form:
<form action="index.html#kontakt" method="post" onsubmit="return checkForm();">
<fieldset>
<div class="form-group" id="error1">
<p id="errorName" class="d-none">Add name!</p>
<label for="contactName">ImiÄ™</label>
<input type="text" id="contactName"/>
</div>
<div class="form-group" id="error2">
<p id="errorLastName" class="d-none">Add last name!</p>
<label for="contactLastName">Nazwisko</label>
<input type="text" id="contactLastName"/>
</div>
<div class="form-group" id="error3">
<p id="errorMail" class="d-none">Add email!</p>
<p id="errorMailCorrect" class="d-none">Wrong email!</p>
<label for="contactEmail">Email</label>
<input type="text" id="contactEmail" />
</div>
<div class="form-group" id="error4">
<p id="errorInfo" class="d-none">Add info!</p>
<p id="errorInfoLength" class="d-none">Limit is 250 chars!</p>
<label for="contactInfo">Informacja</label>
<input type="text" id="contactInfo" />
</div>
<input type="submit" value="Submit" />
</fieldset>
</form>
In bootrap 3.4.1 I could simply add to my .js file:
document.getElementById("error1").className="form-group has-error";
What is the equivalent of "form-group has-error" in Boostrap 4?
Also another question. What do you need to do to make the fields on the form validate the details you have entered immediately? Not after we submitted them.
This is explained in the Bootstrap 4 documentation. You can:
Use the :valid and :invalid CSS pseudo-classes. They only work if the form has the class .was-validated.
Or use the .is-valid and is-invalid CSS classes.
Validating before submitting can be done using standard HTML attributes such as required, pattern, etc.. If that does not cover your requirements, you can do it yourself with JavaScript. But that is a whole other topic and it is probably best to use some library or framework for that.
I'm working on a basic webform for my beginning Javascript class. I pretty much have all my expected results (assignment covers input validation and storing elements in an array by name), except for the fact that when I submit the form, I'd like to give a 5 second delay from the time I hit submit to when the page redirects. This delay is so that user will be able to cancel the order.
From what we have learned in class so far, I would expect I perform this action with a setTimeout block of code- though I haven't been able to work that yet. My form submission is dependent on a true/false return value from the called function, and I'd like to delay that true value from hitting so quickly. I've attached my full HTML file but the block of code that I'm wondering why it isn't working in particular is this:
setTimeout(function() {
return true;
}, 5000);
The first problem I observe when debugging in Chrome is that this doesn't return the True value back to the surrounding code.
I think that something could be done with jQuery to circumvent this but we haven't covered any of that so I'd like to avoid going that route.
```
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="description" content="Costello Improved">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Costellos Pasta and Pizza</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="costello.css">
</head>
<body>
<form name="myForm" action="https://costello-pasta.glitch.me/order" id="myForm" method="POST" onsubmit="return calculateOrder(this)">
<div class="container">
<div class="row">
<div class="col-md-12" id="debug">Costello's Online Orders</div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta Bowl</div>
<div class="col-md-4"> (basic price: $7.50)</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Pasta</div>
<div class="col-md-4">
<div><input type="radio" name="pastatype" value="0" />Spaghetti (no extra cost)</div>
<div><input type="radio" name="pastatype" value="50" />Fettucine (add 50 cents)</div>
<div><input type="radio" name="pastatype" value="75" />Fusilli (add 75 cents)</div>
</div>
<div class="col-md-4 msg" id="radioLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Sauce</div>
<div class="col-md-4">
<select name="sauce">
<option value="0">Pomodoro (no extra cost)</option>
<option value="50">Bolognese (add 50 cents)</option>
<option value="100">Alfredo (add $1.00)</option>
</select>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Extras</div>
<div class="col-md-4">
<div><input type="checkbox" name="extras" value="200" />Side salad (add $2.00)</div>
<div><input type="checkbox" name="extras" value="100" />Bread sticks (add $1.00)</div>
</div>
<div class="col-md-4"></div>
</div>
<div class="row">
<div class="col-md-4 label">Name</div>
<div class="col-md-4"><input type="text" id="name" name="client_name" /></div>
<div class="col-md-4 msg" id="nameLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label">Phone</div>
<div class="col-md-4"><input type="text" id="phone" value="" /></div>
<div class="col-md-4 msg" id="phoneLabel"></div>
</div>
<div class="row">
<div class="col-md-4 label"><input type="submit" value="Order" /></div>
<div class="col-md-4" id="totalcost"></div>
<div class="col-md-4 msg" id="submitMessage"></div>
</div>
</div>
</form>
</body>
<script>
function calculateOrder() {
var totalCost = 750;
//Storing Pasta radio buttons into array. Iterating through array and adding checked selection's value to the total cost.
var submitBool = true;
var pastaArray = document.getElementsByName('pastatype');
for (var i = 0; i < pastaArray.length; i++) {
if (pastaArray[i].checked == true) {
totalCost = totalCost + parseInt(pastaArray[i].value);
}
//Validating Pasta input
}
if (pastaArray[0].checked == false && pastaArray[1].checked == false && pastaArray[2].checked == false) {
document.getElementById('radioLabel').innerHTML = "Required field! (You must choose a pasta)";
submitBool = false;
} else {
document.getElementById('radioLabel').innerHTML = "";
}
//Storing sauce selection into an array. Adding price for selected option.
var sauceArray = document.getElementsByName('sauce');
totalCost = totalCost + parseInt(sauceArray[0].value);
//Storing extras selection(s) into an array. Adding prices for selected options.
var extraArray = document.getElementsByName('extras');
for (var x = 0; x < extraArray.length; x++) {
if (extraArray[x].checked == true) {
totalCost = totalCost + parseInt(extraArray[x].value);
}
}
//Validating Name input
if (document.getElementById('name').value == "") {
document.getElementById('nameLabel').innerHTML = "Required field! Enter your name.";
submitBool = false;
} else {
document.getElementById('nameLabel').innerHTML = "";
}
//Validating Phone Number Input
var phone = document.getElementById('phone').value;
phone = phone.toString();
if (document.getElementById('phone').value == null) {
document.getElementById('phoneLabel').innerHTML = "Required field! Enter your phone number.";
submitBool = false;
} else if (phone[3] != "-") {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else if (phone[7] != "-") {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else if (phone.length > 12 || phone.length < 12) {
document.getElementById('phoneLabel').innerHTML = "Enter in 888-888-8888 format!";
submitBool = false;
} else {
document.getElementById('phoneLabel').innerHTML = "";
}
//Form runs if input has been valid in all input options
if (submitBool == false) {
return false;
} else if (submitBool == true){
var preFixed = totalCost / 100;
var postFixed = preFixed.toFixed(2);
document.getElementById('totalcost').innerHTML = "Total Bill: $" + postFixed;
document.getElementById('submitMessage').innerHTML = "Order is being processed, <a>cancel?</a>"
setTimeout(function() {
return true;
}, 5000);
}
}
</script>
</html>
```
You can use the onSubmit event and delay the usual functionality. I've created a simple demo thus you can understand it easily. Here after form submission it'll submit the form after 5 seconds, or be canceled if you hit Cancel.
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', handleSubmit);
var submitTimer;
function handleSubmit(event) {
console.log('submitTimer set');
event.preventDefault();
submitTimer = setTimeout(() => {
this.submit();
console.log('Submitted after 5 seconds');
}, 5000)
};
function cancel(){
clearTimeout(submitTimer);
console.log('Submit Canceled');
}
<form id="myForm">
<input type="text" name="name"/>
<button type="submit">Submit</button>
<button type="button" onclick="cancel()" >Cancel</button>
</form>
The setTimeout function calls a function or evaluates an expression after a specified number of milliseconds (in your case 5000). What you did in your code was just to return a boolean without creating a channel to get the value after the time has lapsed. Since this code is sort of "asynchronous" (it takes time), you can use the inbuilt Promise function to get the value. In order words, your code could be restructured to something like this:
getTheBoolValue = () => new Promise((resolve, reject) => {
setTimeout(function(){
resolve(true)
},5000)
})
getTheBoolValue().then(data => console.log(data))
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
I have a Magento website and there are some delivery options when ordering a product.
There are 2 methods available.
- pick up yourself
- deliver
When you choose radiobutton "deliver" some div with a textarea is visible.
This textarea needs to be required.
But when you select radiobutton "pick up yourself" the textarea is invisible and needs to be NOT required anymore.
I made a fiddle of the items
Can anyone help me with how to do this?
HTML:
<h2>Select delivery method</h2>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method"> pick up
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method"> deliver
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
If you are after a pure js version you can use this method:
function check() {
var items = document.getElementsByName('shipping_method');
var v = null;
for (var i = 0; i < items.length; i++) {
if (items[i].checked) {
v = items[i].value;
break;
}
}
var required = (v == "tablerate_bestway");
document.getElementById("deliv-hold").style.display = required ? "block" : "none";
if (required) {
document.getElementById("shipping_arrival_comments").setAttribute("required", true);
} else {
document.getElementById("shipping_arrival_comments").removeAttribute("required");
}
}
http://jsfiddle.net/gv7xh4cg/9/
Basically, iterate over items of the same name and see if they are selected, if they are grab the value from it and use that to show or hide the comments div.
Cheers,
Ian
Here you can see an example of code to do so :
$(document).ready(function() {
var submitMessage = "";
$(":radio").change(function() {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
$("#deliv-hold").hide(250);
}
else {
$("#deliv-hold").show(250);
}
});
$("form").submit(function(e) {
var selectedRadio = $("input[name='shipping_method']:checked").val();
if (selectedRadio == "freeshipping_freeshipping") {
submitMessage = "Your command is in process. Thank you for purshasing.";
}
else {
if ($("#shipping_arrival_comments").val().length < 1) {
e.preventDefault();
alert("Field 'delivery date and time' missing.");
submitMessage = "";
}
else {
submitMessage = "Deliver is on his way. Thank you for purshasing.";
}
}
if (submitMessage != "") {
alert(submitMessage);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> Test check </title>
<meta charset = "utf-8" />
</head>
<body>
<span>Choose your delivery method :</span>
<form>
<input type="radio" class="radio" id="s_method_freeshipping_freeshipping" value="freeshipping_freeshipping" name="shipping_method">
<label for="s_method_freeshipping_freeshipping">Pick up yourself</label>
<input type="radio" class="radio" checked="checked" id="s_method_tablerate_bestway" value="tablerate_bestway" name="shipping_method">
<label for="s_method_tablerate_bestway">Deliver</label>
<br />
<div id="deliv-hold">
the delivery date and time:<br>
<textarea id="shipping_arrival_comments" name="shipping_arrival_comments" style="min-width: 265px;" rows="4"></textarea>
</div>
<input type = "submit" id="submit_delivery" name = "submit_delivery" />
</form>
</body>
</html>
I used JQuery include (see below the code the script include) to use the DOM selector which is easier to use than plain javascript.
I updated your fiddle (it also makes the textarea required):
http://jsfiddle.net/gv7xh4cg/4/
You should include jQuery for:
$('input.radio').click(function(){
var selectedOption = $(this).val();
var delivlHold = $('#deliv-hold'),
comments = $('#shipping_arrival_comments');
if(selectedOption === 'freeshipping_freeshipping') {
delivlHold.show();
comments.prop('required',true);
} else {
delivlHold.hide();
comments.prop('required',false);
}
});
and than add display: none:
#deliv-hold{padding-top:20px; display: none}
It does what you asked for.